[Ruby] Rails Tips

less than 1 minute read

Why you can get the value by. (Dot) + column name when accessing the database instance

Because it is an instance (object) created by a class that inherits Active Record, it is possible to get the value using the .method.
Since it is not the usual Ruby notation, I want to get the value for the hash object, so if I write it with dots, an error will occur.

How to get the hash value in Ruby

example.rb


hash = {name: 'hoge', email: '[email protected]'}

hash[:name]
=> "hoge"

# .I get an error when I try to get it with
hash.name
NoMethodError (undefined method `name' for {:name=>"hoge", :email=>"[email protected]"}:Hash)
How to get a value in an object created from a class that inherits AR

example.rb


#Assuming that the Hash class has already been defined, Hash.Create an instance with new
hash = Hash.new(name: 'hoge', email: '[email protected]')

hash[:name]
=> "hoge"

hash.name
=> "hoge"