Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash['key'] to hash.key in Ruby

I have a a hash

foo = {'bar'=>'baz'} 

I would like to call foo.bar #=> 'baz'

My motivation is rewriting an activerecord query into a raw sql query (using Model#find_by_sql). This returns a hash with the SELECT clause values as keys. However, my existing code relies on object.method dot notation. I'd like to do minimal code rewrite. Thanks.

Edit: it appears Lua has this feature:

point = { x = 10, y = 20 }   -- Create new table print(point["x"])            -- Prints 10 print(point.x)               -- Has exactly the same meaning as line above 
like image 203
user94154 Avatar asked Nov 18 '09 02:11

user94154


People also ask

How do I change the key of a hash in Ruby?

This is a pretty neat snippet of Ruby that I found to rename a key in a Ruby hash. The #delete method on a hash will return the value of the key provided while removing the item from the hash. The resulting hash gets a new key assigned to the old key's value.

What can be a hash key in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

How do you make hash hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.

How do I get the hash key?

Simply pressing alt and 3 at the same time will insert a # hash symbol into your text in any application. This shortcut will work with all versions of Mac OS X whether you have a Macbook, Air or an iMac. In most cases Apple has decided to replace this key with a symbol of the local currency.


1 Answers

>> require 'ostruct' => [] >> foo = {'bar'=>'baz'} => {"bar"=>"baz"} >> foo_obj = OpenStruct.new foo => #<OpenStruct bar="baz"> >> foo_obj.bar => "baz" >> 
like image 140
Hooopo Avatar answered Sep 18 '22 16:09

Hooopo