argius note

プログラミング関連

暗黙の文字列変換

暗黙に文字列への変換をさせるには、to_strメソッドを定義する。

class Name
  def initialize name
    @name = name
  end
  def to_str
    return "name is " + @name
  end
end
o = Name.new "A.T"
p o
p "My " + o
puts o
puts "My " + o

実行するとこうなる。

#
"My name is A.T"
#
My name is A.T

to_strを定義せずに暗黙の型変換を行おうとするとエラー。to_strを消して実行すると、こうなる。

string.rb:12:in `+': cannot convert Name into String (TypeError)
	from string.rb:13