Ruby case ... when
When using case ... when in ruby it is important to note the way how classes are compared
1 === 1
=> true
Fixnum === Fixnum
=> false
So
obj = 'hello'
case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string')
end
Will print "It is not a string".
However,
obj = 'hello'
case obj # was case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string')
end
Will work the way we expect it to.
This is because the ===
operator has been defined so that it returns true if you apply it over a class and an instance of that class.
Written by Amit Kumar
Related protips
1 Response
Interesting :) thanks!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#