Case (variable) when type1 ... when type2 ... end

Hi all,
how can I write case statement to check of specific type the variable
has?
Something like:

case var
when :Fixnum
puts “#{var} is Fixnum”
when :String
puts “#{var} is String”
end

I tried this also

case var.class
when ‘Fixnum’
puts “#{var} is Fixnum”
when ‘String’
puts “#{var} is String”
end

but ruby refuses to understand me :frowning:
What is the best way to write conditional that depends of variable type?

Thank you!

how can I write case statement to check of specific type the variable has?
Something like:

It simpler:

case var
when :Fixnum
puts “#{var} is Fixnum”
when :String
puts “#{var} is String”
end

case var
when Fixnum
puts “#{var} is Fixnum”
when String
puts “#{var} is String”
end

(no “:”)

Cheers,

oh, I was almost there :stuck_out_tongue:
Thank you !

Eugen,

Monday, August 30, 2010, 12:39:36 AM, you wrote:

EC> Hi all,
EC> how can I write case statement to check of specific type the
variable has?
EC> Something like:

EC> case var
EC> when :Fixnum
EC> puts “#{var} is Fixnum”
EC> when :String
EC> puts “#{var} is String”
EC> end

EC> I tried this also

EC> case var.class
EC> when ‘Fixnum’
EC> puts “#{var} is Fixnum”
EC> when ‘String’
EC> puts “#{var} is String”
EC> end

EC> but ruby refuses to understand me :frowning:
EC> What is the best way to write conditional that depends of variable
type?

EC> Thank you!

You were very close.

case var
when Fixnum
puts “#{var} is Fixnum”
when String
puts “#{var} is String”
end

Ralph

On 08/30/10 10:33, Jean-Julien F. wrote:

end
Cheers,

Hi, could you explain me why this works? It’s a special behaviour of the
“case” statment?

No, it’s not a special behavior. Explanation is here.

http://ruby.about.com/od/beginningruby/qt/On-Case-And-Class.htm

On Fri, Sep 3, 2010 at 7:25 AM, tilde [email protected] wrote:

puts “#{var} is Fixnum”

(no “:”)

Cheers,

Hi, could you explain me why this works? It’s a special behaviour of the
“case” statment?

“case” uses operator “===” to check conditions. If you do “case x
when y” then “y === x” is invoked to check the condition (note the
order of x and y). You can even cook your own

positive = lambda {|x| x >= 0}
class << positive
alias :=== :call
end

(-4…4).each do |i|
case i
when positive
puts “#{i} pos”
else
puts “#{i} neg”
end
end

btw, there is also another form of case

case # no value here!
when i >= 0
puts “#{i} pos”
else
puts “#{i} neg”
end

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs