Hash with key and value from ActiveRecord?


#1

Heya,

I think I have thinking barrier. I just want a simple hash out of an
ActiveRecord.

@attributes = Attribute.find_all_by_character_id(@character).hash {
|u| [u.name, u.value] }

and I would like to access it like

@attributes[:health]

but it doesn’t work. Anyone can help me out with that?


#2

Try this:

@attributes = Hash[*Attribute.find_all_by_character_id(@character).map
{ |a| [a.name, a.value] }.flatten]

On Mar 25, 7:46 am, Heinz S. removed_email_address@domain.invalid


#3

On Mar 25, 11:46 am, Heinz S. removed_email_address@domain.invalid
wrote:

@attributes = Attribute.find_all_by_character_id(@character).hash {
|u| [u.name, u.value] }

and I would like to access it like

@attributes[:health]

but it doesn’t work. Anyone can help me out with that?

The keys of your hash are strings, not symbols. (be careful with an
instance variable called @attributes if this is in an instance method

  • you would overwrite activerecord’s instance variable of the same
    name)

Fred


#4

I just renamed @attributes but using ‘health’ instead of :health doesn’t
really help…


#5

I actually don’t get the OP’s use of the hash method in this context:
http://www.ruby-doc.org/core/classes/Array.html#M002182

It seems that it’s just computing the hash, and the block passed is
just being silently ignored…
Heniz, using your code what’s the output of @attributes.inspect and
@attributes.class.name?

On Mar 25, 8:33 am, Frederick C. removed_email_address@domain.invalid


#6

On Mar 25, 12:48 pm, Heinz S. removed_email_address@domain.invalid
wrote:

I just renamed @attributes but using ‘health’ instead of :health doesn’t
really help…

There’s also what Harold said - that hash method isn’t doing what you
think it is.

Fred


#7

Frederick C. wrote:

On Mar 25, 12:48�pm, Heinz S. removed_email_address@domain.invalid
wrote:

I just renamed @attributes but using ‘health’ instead of :health doesn’t
really help…

There’s also what Harold said - that hash method isn’t doing what you
think it is.

Fred

Oh yeah, I overlooked his first post. Works like a charm, thanks :slight_smile: