Re: How to compare a hash key with a string value
Robert Klemme <[email protected]> Thu, 24 Oct 2019 12:55:12 +0200
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAM9pMnN1ubeaffyOQJ508bLgF24ZTJmRoP-GVe37xDRkjrcBSw@mail.gmail.com> |
A few remarks inline below. On Wed, Oct 23, 2019 at 7:36 PM Tran, Minh <[email protected]> wrote: > Hello, > I am having a scenario which I want to print out the value of a hash > element when its key equals to a string value such as "width". > I try several alternatives but so far I have had a good result. > So if you know on how to do , please share it with me. > > My hash table array looks like as the following: > > hash = > [{"label":"Name","value":"Bob","identifier":"field2","type":"oneLineText","page":1,"page_name":"Step > 1","width":"100%"},{"label":"Email","value":"[email protected]","identifier":"field3","type":"email","page":1,"page_name":"Step > 1","width":"100%"},{"label":"Phone > Number","value":"","identifier":"field7","type":"oneLineText","page":1,"page_name":"Step > 1","width":"100%"},{"label":"Comments","value":"some information about the > compagny","identifier":"field5","type":"textarea","page":1,"page_name":"Step > 1","width":"100%"}] > The name of the variable is misleading. This is actually an Array of Hash, so "hashes" would be more appropriate. > My Ruby code is as the following where I need to print out the hash value > when the hash key equals to "width" > > > i = 0 > hash.each do |person| > i += 1 > puts "Person is #{i}" > person.each do |key, value| > You are not actually using the Hash as a hashtable with fast lookups here. > > if key == "width" > puts "The value of width is #{value}" > end > > > end > end > > I would do hashes.each_with_index do |h, i| puts "Person: #{i}" width = h["width"] and puts "The value of width is #{width}" end This is more efficient than checking with #has_key? because it requires just a single hash lookup vs. two. If you want a printout also for nil and false you could do hashes.each_with_index do |h, i| puts "Person: #{i}" match = h.assoc(:width) and puts "The value of width is #{match.last}" end Cheers robert Unsubscribe: <mailto:[email protected]?subject=unsubscribe> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>