I've found in case / when if the case is about a class :
case my_var.class
when String then puts my_var
when Array then my_var.each {|v| puts v}
end
doesn't work i do have to use :
case my_var.class.to_s
when 'String' then puts my_var
when 'Array' then my_var.each {|v| puts v}
end
why ?
(with ruby 1.9.x)
···
--
« Le verbe aimer est difficile à conjuguer :
son passé n'est pas simple, son présent n'est qu'indicatif,
et son futur est toujours conditionnel. »
(Jean Cocteau)
I've found in case / when if the case is about a class :
case my_var.class
when String then puts my_var
when Array then my_var.each {|v| puts v}
end
doesn't work i do have to use :
case my_var.class.to_s
when 'String' then puts my_var
when 'Array' then my_var.each {|v| puts v}
end
why ?
"when" condition in case statement uses === to compare objects. For
strings a = b is true if a and b have the same characters, however
String === String is false:
a = "Hello"
=> "Hello"
b = "Hello"
=> "Hello"
a === b
=> true
String === String
=> false
BTW "===" is a method:
a.===(b)
=> true
so you can define your own rules when objects should be considered equal:
class Marble
attr_accessor :size, :color
def initialize(size, color)
self.size = size
self.color = color
end
it says it returns true if the object is *an instance* of this class.
So you don't have to pass the class, but the object itself:
case my_var
when String then puts my_var
when Array then my_var.each {|v| puts v}
end
irb(main):003:0> def test var
irb(main):004:1> case var
irb(main):005:2> when String then puts var
irb(main):006:2> when Array then var.each {|v| puts v}
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0> test "hello"
hello
=> nil
irb(main):010:0> test [1,2,3]
1
2
3
=> [1, 2, 3]
i do have to use :
case my_var.class.to_s
when 'String' then puts my_var
when 'Array' then my_var.each {|v| puts v}
end
You can also do this, but the above is cleaner.
Jesus.
···
2010/6/11 Une Bévue <unbewusst.sein@google.com.invalid>:
For strings a = b is true if a and b have the same characters
err, I ment a === b . For strings a === b is the same as a == b.
That's mostly true for other objects too (if they don't override ===
),
but not always.
Jesús Gabriel y Galán <jgabrielygalan@gmail.com> wrote:
You can also do this, but the above is cleaner.
--
« Le verbe aimer est difficile à conjuguer :
son passé n'est pas simple, son présent n'est qu'indicatif,
et son futur est toujours conditionnel. »
(Jean Cocteau)
--
« Le verbe aimer est difficile à conjuguer :
son passé n'est pas simple, son présent n'est qu'indicatif,
et son futur est toujours conditionnel. »
(Jean Cocteau)