Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Object | public_send

概要

Object#public_send(name, *args) -> object

詳細

オブジェクトの public メソッド name を args を引数にして呼び出し、メソッ ドの実行結果を返却。
send とは異なり、 public メソッドのみを対象とする。

サンプルコード
class Hoge
  def public_hoge(msg)
    'public_hoge:' + msg
  end

  protected

  def protected_hoge(msg)
    'protected_hoge:' + msg
  end

  private

  def private_hoge(msg)
    'private_hoge:' + msg
  end
end

hoge = Hoge.new
puts hoge.public_send :public_hoge, "hoge"
begin
  hoge.public_send :protected_hoge, "hoge"
rescue => e
  puts e
end

begin
  hoge.public_send :private_hoge, "hoge"
rescue => e
  puts e
end

puts hoge.send :public_hoge, "hoge"
puts hoge.send :protected_hoge, "hoge"
puts hoge.send :private_hoge, "hoge"

出力

public_hoge:hoge
protected method `protected_hoge' called for #<Hoge:0x2a06600>
private method `private_hoge' called for #<Hoge:0x2a06600>
public_hoge:hoge
protected_hoge:hoge
private_hoge:hoge