Home > Software design >  Use of send keyword in Ruby Class
Use of send keyword in Ruby Class

Time:03-20

I am very new to Ruby, so I am having difficulty understanding the functionality of the code.

I have a class having a structure given below.

1. class MyClass::Container
2.   def self.call
3.     @containers || {}
4.   end
5. 
6.   def self.[] namespace
7.     @containers ||= Hash.new{|h, k| h[k] = new }
8.     @containers[namespace]
9.   end
10. 
11.  def add_flag name
12.    self.class.attr_reader name
13.  end

Then I have another module having a structure given below.

1. module MyClass::MyFlag
2.   def self.enabled? flag, value = "true", identifier: nil
3.     if identifier
4.       MyClass::Container[namespace].send(name).value(identifier: identifier) == value
5.     else
6.      MyClass::Container[namespace].send(name).value == value
7.     end
8.   end
9. end

I am having a problem understanding how line no 4 & 6 are working in MyClass::MyFlag. I mean how the .send .value is working ?.

CodePudding user response:

MyClass::Container[namespace]

is an object.

.send(name)

sends the message in name to that object. E.g.

.send(:foo)

sends :foo to that object as if it were called like obj.foo. That expression returns another object.

.value

sends the message :value to the object returned by .send(name), as if it were called like

`.send(name).send(:value)`

And that returns another object.

CodePudding user response:

Ruby is a method call language, but using the combination of respond_to? and send you can make it seem like a message passing language.

For example here is a simple method that will "send a message" to an object, if the message corresponds to a method that exists on the receiver object, the object will respond with the result of the method call. However if the method does not exist, it will simply respond with a message indicating that the message is not understood, ie the receiver does not have a matching method"

def send_msg(receiver, msg)
  receiver.respond_to?(msg) ? "I understood that message and my reply is #{receiver.send(msg)}" : "I don't understand that message"
end

For example a string object has a method size but does not have a method foo, so here are the results of sending these messages to a string some_string

send_msg("some_string", "size")
=> "I understood that message and my reply is 11"

but sending a message that does not correspond to a method returns the following;

send_msg("some_string", "foo")
=> "I don't understand that message"
  • Related