Skip to content

Commit 953e1ef

Browse files
committed
Make invalid & operator type error message consistent with */**
If #to_proc is defined, this uses the following error message format, matching the error message format used for * when to_a returns non-Array and for ** when to_hash returns non-Hash: ``` can't convert ClassName to Proc (ClassName#to_proc gives OtherClassName) ``` If #to_proc is not defined, this uses the following error message format, matching the error message format used when ** is called on a non-Hash not implementing to_hash. ``` no implicit conversion of ClassName into Proc ``` There isn't a similar error for * when called on a non-Array not implementing to_a, as Ruby does not raise for that case. Fixes [Bug #21563]
1 parent 5c87551 commit 953e1ef

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

test/ruby/test_exception.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1525,4 +1525,31 @@ def detailed_message(**)
15251525
assert_in_out_err(%W[-r#{lib} #{main}], "", [], [:*, "\n""path=#{main}\n", :*])
15261526
end
15271527
end
1528+
1529+
class Ex; end
1530+
1531+
def test_exception_message_for_unexpected_implicit_conversion_type
1532+
a = Ex.new
1533+
def self.x(a) = nil
1534+
1535+
assert_raise_with_message(TypeError, "no implicit conversion of TestException::Ex into Hash") do
1536+
x(**a)
1537+
end
1538+
assert_raise_with_message(TypeError, "no implicit conversion of TestException::Ex into Proc") do
1539+
x(&a)
1540+
end
1541+
1542+
def a.to_a = 1
1543+
def a.to_hash = 1
1544+
def a.to_proc = 1
1545+
assert_raise_with_message(TypeError, "can't convert TestException::Ex to Array (TestException::Ex#to_a gives Integer)") do
1546+
x(*a)
1547+
end
1548+
assert_raise_with_message(TypeError, "can't convert TestException::Ex to Hash (TestException::Ex#to_hash gives Integer)") do
1549+
x(**a)
1550+
end
1551+
assert_raise_with_message(TypeError, "can't convert TestException::Ex to Proc (TestException::Ex#to_proc gives Integer)") do
1552+
x(&a)
1553+
end
1554+
end
15281555
end

vm_args.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,9 +1045,17 @@ vm_to_proc(VALUE proc)
10451045
}
10461046

10471047
if (NIL_P(b) || !rb_obj_is_proc(b)) {
1048-
rb_raise(rb_eTypeError,
1049-
"wrong argument type %s (expected Proc)",
1050-
rb_obj_classname(proc));
1048+
if (me) {
1049+
VALUE cname = rb_obj_class(proc);
1050+
rb_raise(rb_eTypeError,
1051+
"can't convert %"PRIsVALUE" to Proc (%"PRIsVALUE"#to_proc gives %"PRIsVALUE")",
1052+
cname, cname, rb_obj_class(b));
1053+
}
1054+
else {
1055+
rb_raise(rb_eTypeError,
1056+
"no implicit conversion of %s into Proc",
1057+
rb_obj_classname(proc));
1058+
}
10511059
}
10521060
return b;
10531061
}

0 commit comments

Comments
 (0)