franz franz - 1 year ago 64
Ruby Question

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

I'm trying to understand the following Ruby code.

It looks like

is a hash that gets passed as an argument with a default value of an empty hash.

iterates over the key, value pairs in the hash (

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

def initialize(attrs = {}, *args)
attrs.each do |k,v|
self.send "#{k}=", v

Answer Source

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 = "John Smith"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download