LoginSignup
1
0

More than 5 years have passed since last update.

第13回つぶやき勉強会 ~ プライベートの侵害 ~

Last updated at Posted at 2017-04-04
1 / 6

メソッドが4つあります

class Hoge
  def hoge1; piyo;             end
  def hoge2; self.piyo;        end
  def hoge3; self.send(:piyo); end
  def hoge4; self&.piyo;       end

  private
    def piyo; 'Good'; end
end
h = Hoge.new

4つのインスタンスメソッドを実行すると、それぞれ何が返りますか?

h.hoge1
h.hoge2
h.hoge3
h.hoge4

(1..4).each do |i|
  begin
    puts "hoge#{i}:" + h.send("hoge#{i}".to_sym)
  rescue => e
    puts "hoge#{i}:'#{e}'"
  end
end;

解答

hoge1:Good
hoge2:'private method `piyo' called for #<Hoge:0x007f8142c02770>'
hoge3:Good
hoge4:'private method `piyo' called for #<Hoge:0x007f8142c02770>'

あとがき

ぼくは、h.try(:piyo) を勘違いしていました。これは、&. と同じような扱いになります。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0