Need some help with hashes, don't know what fails

Hi all,

I have a hash that contains other hashes, now I’m trying to retreive the
information on those but I can’t get the values inside.

Just this code for explain what happens to me:

Im using ruby-1.9.2-p136.

## just a sample notifications = Hash.new

notifications[‘1’] = { what: ‘text’, who: ‘Antonio’, when: Time.now}
notifications[‘2’] = { what: ‘text’, who: ‘Alfonso’, when: Time.now}
notifications[‘3’] = { what: ‘text’, who: ‘Alberto’, when: Time.now}

notifications.each do |key, value|
puts key.inspect # Getting: ‘1’, ‘2’,‘3’ correct
puts value.inspect # Getting: { what: ‘text’, who:
‘Antonio’, when: Time.now} and so on. Correct
puts value.class # Getting: Hash. Correct
puts value.has_key?(‘what’) # Getting false. Incorrect
puts value.has_key?(‘when’) # Getting false. Incorrect
puts value.has_key?(‘data’) # Getting false. Incorrect

I get the values…

value.each do | k, v |
puts “#{k}: #{v}”
end
end

Thanks in advance.

Take another look at value.inspect. Those hash keys are symbols, not
strings. value.has_key? :what et al should work.

On Mon, Oct 3, 2011 at 12:42 AM, Antonio Fernández vara

{ what: ‘text’, who: ‘Antonio’, when: Time.now}
is in fact
{ :what => ‘text’, :who => ‘Antonio’, :when => Time.now }

the keys are symbols, not strings

so you must

puts value.has_key?(:what)

On Oct 3, 3:42am, Antonio Fernández vara
[email protected] wrote:

just a sample

notifications = Hash.new

notifications[‘1’] = { what: ‘text’, who: ‘Antonio’, when: Time.now}
notifications[‘2’] = { what: ‘text’, who: ‘Alfonso’, when: Time.now}
notifications[‘3’] = { what: ‘text’, who: ‘Alberto’, when: Time.now}

If this is an accurate portrayal of your hash-of-hashes in the real
code, I suggest you consider an array-of-hashes instead.

On Tue, Oct 4, 2011 at 2:21 AM, Yossef M. [email protected]
wrote:

code, I suggest you consider an array-of-hashes instead.
Or even an array of Structs, e.g.

Item = Struct.new :what, :who, :when

notifications = [
Item[‘text’, ‘Antonio’, Time.now],
Item[‘text’, ‘Antonio’, Time.now],
Item[‘text’, ‘Antonio’, Time.now],
]

Kind regards

robert

Thanks both, now I understand I’m doing correctly the hashes.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs