Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use hash keys as methods on a class?

Tags:

ruby

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
like image 781
Michael Avatar asked Feb 10 '10 21:02

Michael


People also ask

What does hash do in Ruby?

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.

How do I get the hash value in Ruby?

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.

How can you tell if a key is present in a hash?

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.


1 Answers

Just use OpenStruct:

require 'ostruct'
class User < OpenStruct
end

u = User.new :sn => 222
u.sn
like image 144
Alexey Avatar answered Sep 19 '22 17:09

Alexey