Friday, January 04, 2008

'send' in Ruby

send

Calling a method when method name is stored as a string object in a variable i.e. you can not see which method to call.


example 1
when method name is simply stored as a String object

  1. class C
  2. def wish
  3. p "hello world"
  4. end
  5. end
  6. a = "wish"
  7. c = C.new
  8. c.send(a)

example 2
making set method at runtime

  1. class C
  2. attr_accessor :name
  3. end

  4. c = C.new

  5. a = "name"

  6. c.send(a + "=", "Arun")

  7. p c.send(a)

example 3
this is interesting, when attribute name itself is send

  1. class C
  2. attr_accessor :send
  3. end

  4. c = C.new

  5. a = "send"

  6. c.__send__(a + "=", "Arun")

  7. p c.__send__(a) # => Arun

0 comments: