🐙
[Bug #21563] ブロック引数に意図しないオブジェクトを渡したときのエラーメッセージが適切でないチケット
[Bug #21563] Misleading error message when to_proc does not return a Proc in an Object used as a &block argument
- ブロック引数に
Proc以外のオブジェクトを渡した場合に内部で暗黙的に#to_procを呼び出し、その戻り値をブロック引数として扱うようになっている
class SayHi
def to_proc
proc { "hello" }
end
end
def callablock(&block)
block.call
end
# SayHi#to_proc の結果が callablock のブロック引数として渡される
pp callablock(&SayHi.new)
# => "hello"
- このときの
#to_procはProcオブジェクトを返す必要がありProc以外のオブジェクトを返したときは次のようなエラーになる
class SayHi
def to_proc
# Proc を返さない
"hello"
end
end
def callablock(&block)
block.call
end
# error: wrong argument type SayHi (expected Proc) (TypeError)
pp callablock(&SayHi.new)
- このときのエラーメッセージが『
SayHiの型が間違っている』となっており適していないというバグ報告 - 本来であれば以下のようなエラーメッセージを期待する
wrong argument type String (expected Proc)
- これなんですが
#to_aや#to_hashでは以下のようなエラーメッセージになっているのでそれとあわせるとよい、とコメントされていますね
A = Class.new
a = A.new
def a.to_a = 1
def a.to_hash = 1
# これらも Array や Hash が戻り値であることを期待するエラーになる
p(*a) # can't convert A to Array (A#to_a gives Integer) (TypeError)
p(**a) # can't convert A to Hash (A#to_hash gives Integer) (TypeError)
- これに合わせて開発版の Ruby 3.5-dev ではエラーメッセージが修正された
class SayHi
def to_proc
# Proc を返さない
"hello"
end
end
def callablock(&block)
block.call
end
pp callablock(&SayHi.new)
# Ruby 3.4 => wrong argument type SayHi (expected Proc) (TypeError)
# Ruby 3.5 => can't convert SayHi to Proc (SayHi#to_proc gives String) (TypeError)
Discussion