Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling self.send iteratively on a hash argument to initialize()

Tags:

ruby

I'm trying to understand the following Ruby code.

It looks like attrs is a hash that gets passed as an argument with a default value of an empty hash.

Then attrs.each iterates over the key, value pairs in the hash (|k,v|).

What effect is achieved by calling self.send on the elements of the key value pair during this iteration?

def initialize(attrs = {}, *args)
  super(*args)
  attrs.each do |k,v|
    self.send "#{k}=", v
  end
end
like image 857
franz Avatar asked Jun 10 '09 02:06

franz


1 Answers

send calls the method in the first parameter, and passes the rest of the parameters as arguments.

In this case I assume what's in attrs is a list of attributes. Let's say it's something like this:

{ :name => "John Smith" }

So then in the loop, it does this:

self.send "name=", "John Smith"

which is equivalent to

self.name = "John Smith"
like image 178
Sarah Mei Avatar answered Oct 11 '22 23:10

Sarah Mei