Hash with key and value from ActiveRecord?

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?

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. [email protected]

On Mar 25, 11:46 am, Heinz S. [email protected]
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

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

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. remo[email protected]

On Mar 25, 12:48 pm, Heinz S. [email protected]
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

Frederick C. wrote:

On Mar 25, 12:48�pm, Heinz S. [email protected]
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:

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