I’m surprised:
x = 1
case x
when 5; puts "5"
when 42; puts "42"
when /abc/; puts "matches /abc/"
when “xyz”; puts "xyz"
end
This is a TypeError. Is there any good reason why?
I think it would make sense for Regex#=== (if not Regex#=~) to return
false for non-Strings. Otherwise, this kind of case statement has to be
broken into an ‘if…else…end’ and two ‘case…end’ statements.
Anyway this workaround is no good for me because, instead of a case
statement, I have a list of given objects which respond to :===. I guess
I could test for Regex, but that’s not very elegant. Also, I can’t just
rescue TypeError, because I can’t be sure that a given (user-supplied)
object uses TypeError in this way (and maybe the TypeError is a
programming error inside the user’s #=== implementation).
The same goes for Range#=== .
x = 1
puts case
when x == 5; “5”
when x == 42; “42”
when /abc/ =~ x.to_s; “matches /abc/”
when “xyz” == x.to_s; “xyz”
else “none”
end
case without a statement matches any expression that evaluates to a
non-false, non-nil argument
Hope that’s what you want
···
On Wed, 18 Dec 2002, Joel VanderWerf wrote:
x = 1
case x
when 5; puts “5”
when 42; puts “42”
when /abc/; puts “matches /abc/”
when “xyz”; puts “xyz”
end
–
Greg Millam
walker at deafcode.com
Greg Millam wrote:
x = 1
case x
when 5; puts “5”
when 42; puts “42”
when /abc/; puts “matches /abc/”
when “xyz”; puts “xyz”
end
x = 1
puts case
when x == 5; “5”
when x == 42; “42”
when /abc/ =~ x.to_s; “matches /abc/”
when “xyz” == x.to_s; “xyz”
else “none”
end
case without a statement matches any expression that evaluates to a
non-false, non-nil argument
Hope that’s what you want
Thanks, but no. I happily discovered that fact a few days ago, but my
real interest here is not case but a list of objects that respond to
:=== (and that’s all I know about them), and a piece of code that
iterates over them looking for a match with a fixed object. I don’t know
whether that fixed object has a #to_s method, or what its semantics are,
so I can’t use it. Anyway, I don’t want to lose the distinction between
Object and “Object”.
···
On Wed, 18 Dec 2002, Joel VanderWerf wrote:
Yukihiro Matsumoto wrote:
Hi,
I’m surprised:
x = 1
case x
when 5; puts “5”
when 42; puts “42”
when /abc/; puts “matches /abc/”
when “xyz”; puts “xyz”
end
This is a TypeError. Is there any good reason why?
No. I will fix this in the development version. And I confirmed no
other === method raise TypeError exception.
matz.
Great. By “other”, I assume you mean besides Regex and Range…
Thanks!
···
In message “Regex#=== with non-string argument” > on 02/12/18, Joel VanderWerf vjoel@PATH.Berkeley.EDU writes: