Re: How to compare a hash key with a string value

Dan Fitzpatrick <[email protected]> Fri, 25 Oct 2019 12:30:45 +0800
Newsgroups gmane.comp.lang.ruby.general
Message-ID <[email protected]>
Hello Dun,


First I would change the name of your variable "hash" to something else 
because it is not a hash, it is an array of hashes. Since it represents 
a list of people, I would call it people.


The main issue is that your keys are getting converted to symbols. So 
none of the objects have the "width" attribute as a string.


This is the only thing that continuously annoys me about Ruby:


a = 
{"label":"Name","value":"Bob","identifier":"field2","type":"oneLineText","page":1,"page_name":"Step 
1","width":"100%"}

=> {:label=>"Name", :value=>"Bob", :identifier=>"field2", 
:type=>"oneLineText", :page=>1, :page_name=>"Step 1", :width=>"100%"}


b 
={"label"=>"Name","value"=>"Bob","identifier"=>"field2","type"=>"oneLineText","page"=>1,"page_name"=>"Step 
1","width"=>"100%"}
=> {"label"=>"Name", "value"=>"Bob", "identifier"=>"field2", 
"type"=>"oneLineText", "page"=>1, "page_name"=>"Step 1", "width"=>"100%"}

a['width']

=> nil

b['width']

=> "100%"

a[:width]

=> "100%"


Here is your code working:

people = 
[{"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%"}]


# If you only need the width attribute, you can do this (no loop on the 
attributes needed):

people.each_with_index do |person, i|
   puts "Person is #{i+1}" # First person displays as 1 instead of 0

   puts "The value of width is #{person[:width]}" if person.has_key?(:width)
end


# If needed, loop through all the attributes of person (like in your 
example), but change to detecting symbol keys

people.each_with_index do |person, i|
   puts "Person is #{i+1}" # First person is 1 instead of 0

   person.each do |key, value|
     if key == :width
       puts "The value of width is #{value}"
     end
   end
end


Also, if you are defining your hashes, you don't need to use JSON format 
with quoted keys, you can just do:

a = {label: "Name", value: "Bob", identifier: "field2", type: 
"oneLineText", page: 1, page_name: "Step 1", width: "100%"}


Dan


On 10/24/2019 1:35 AM, Tran, Minh wrote:

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>