I have a class and a hash. How can I get the members of the hash to dynamically become methods on the class with the key as the method name?
class User
def initialize
@attributes = {"sn" => "Doe", "givenName" => "John"}
end
end
For example, I would like to be able to have the following output Doe
:
u = User.new
puts u.sn
Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values.
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
Just use OpenStruct:
require 'ostruct'
class User < OpenStruct
end
u = User.new :sn => 222
u.sn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With