From: David Masover Date: 2009-12-08T05:54:53+09:00 Subject: Re: convert string into a variable object On Monday 07 December 2009 02:35:39 pm Ad Ad wrote: > I have a file with a list of cities in it. The file is a daily feed and > the cities in it change daily. [snip] > this would give us @toronto = 1, @miami = 1, etc. Is 1 significant? That is, are you trying to count the number of cities, or are you just trying to set them to true? > I have subclasses which would read user input and if that city variable > has been defined already then move ahead. > it would be a simple if statement > if @toronto > ... > end In that case, it would be _much_ more readable if you did @toronto = true rather than @toronto = 1 They'll do the same thing here, but consider this: @toronto = 0 That would be false, right? Wrong. Anything that's not false or nil is a true value in Ruby. You're MUCH better off explicitly using true and false, if that's really what you wanted. If it was meant to be a count, you'd probably want something like: if @toronto > 0 but I have no idea why a count would make sense here, anyway. > I could create a hash map too Yes, you should do that. The downsides of using instance variables for that are much larger than the downsides of doing a little extra typing with: if @cities['toronto'] > but this is the easiest way to do since it No it's not. You had to come here and ask if it was even possible. You already know a hash map is possible, and yo probably already know how to do it. Just in case someone tells you how to use variables instead, here's one very simple reason it's a bad idea: Instance variables have symbols assigned to them. Last I checked, symbols aren't garbage collected, so doing it your way will result in a (very small) memory leak in your program. That won't happen with a hash of strings. > doesnt require the creation of any sort of a container variable. Why is this a problem? I mean, is it the _creation_ of this that's holding you back? That's a single line: @cities = {} Put it in initialize.