basyura's blog

あしたになったらほんきだす。

public_send

1.9 から追加された Kernel#public_send
send と違って private メソッドを呼び出せない。

class A
  def say
    hello
  end
  private 
  def hello
    puts 'hello'
  end
end

A.new.send :say   #=> hello
A.new.send :hello #=> hello

A.new.public_send :say #=> hello
A.new.public_send :hello
#=> `public_send': private method `hello'
#    called for #<A:0x0000010086c828> (NoMethodError)

安全(?)な呼び出しを明示する感じだけど、実際のところ使いどころが有るんだろうか。

1.9.2 を grep してみたところ 1 件ヒット。

#matrix.rb
module CoercionHelper # :nodoc:
   #    
   # Applies the operator +oper+ with argument +obj+
   # through coercion of +obj+
   #    
   def apply_through_coercion(obj, oper)
     coercion = obj.coerce(self)
     raise TypeError unless coercion.is_a?(Array) && coercion.length == 2 
     coercion[0].public_send(oper, coercion[1])
   rescue
     raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}"
   end