From: Walton Hoops Date: 2009-12-09T05:57:03+09:00 Subject: Re: convert string into a variable object > -----Original Message----- > From: Robert Klemme [mailto:shortcutter@googlemail.com] > > 2009/12/8 David A. Black : > > HI -- > > > > On Tue, 8 Dec 2009, Steve Wilhelm wrote: > > > >> Toon Willems wrote: > >>> > >>> On 07 Dec 2009, at 21:35, Ad Ad wrote: > >>> > >>>>> to do. > >>>> > >>>> doesnt require the  creation of any sort of a container variable. > >>>> -- > >>>> Posted via http://www.ruby-forum.com/. > >>>> > >>> > >>> A much better way to do this would be to store the city names in a > hash. > >>> your code would then be: > >>> > >>> File.open(@file). each do |x| > >>>  @hash[x] = true > >>> end > >> > >> Would it not be better to convert to symbols? That is: > >> > >> File.open(@file). each do |x| > >>  @hash[x.strip.to_sym] = true > >> end > >> > >> if @hash[:toronto] > >> or > >> if @hash[:"palo alto"] > >> > >> or > >> > >> if @hash[city.to_sym] > > > > In addition to the garbage collection issue that David M. pointed > out, > > symbols seem an odd choice to me for city names. I always think of > > symbols as appropriate for label-like functionality and values taken > > from a limited set. Strings are a better choice for general > > representation of text. > > I would certainly use String for city names. Hard encoding city names > in classes which would be regenerated over and over again is not a > good solution. Basically, you want to stick all city names as keys in > a Hash and work from there. The mere fact that Ruby is able to > generate local, instance or global variables at runtime does not mean > it is a proper means in all cases. The use case at hand does not call > for meta programming - it just needs a data structure which can work > with appropriate key values. A Hash seems like a good fit here. Now perhaps I'm missing something, but the impression I got was that while the contents of the file changes daily, he doesn't want to remove old cities. Rather he wants to ensure he's not creating duplicates. My solution (to the problem as I understand it) would be to use sets, but if he's not actually wanting to remove anything, I don't think Strings vs. Symbols should matter. Example of set solution: irb(main):001:0> require 'set' => true irb(main):002:0> cities=Set.new => # irb(main):003:0> cities << 'Austin, Texas' => # irb(main):004:0> cities << 'Boring, Oregon' => # irb(main):005:0> cities << 'Boise, Idaho' => # irb(main):006:0> cities << 'Boring, Oregon' => # irb(main):008:0> cities.include? 'Boring, Oregon' => true irb(main):009:0> Is there something I'm missing?