Why doesn't "case" with "when > 2" work?
Why is this not working?
case ARGV.length
when 0
abort "Error 1"
when 开发者_StackOverflow> 2
abort "Error 2"
end
It's not valid ruby syntax.
What you need is
case
when ARGV.length == 0
abort "Error 1"
when ARGV.length > 2
abort "Error 2"
end
When you write case x
, the important part you need to understand is that ruby takes the x and then applies a comparison to the argument or expressions you insert in the when
clause.
The line where you say when x >2
reads to ruby like:
if ARGV.length == > 2
When you remove a specific object from the case
statements, you can apply conditionals within the when
statements .
Use 1.0 / 0.0
to get infinity, which fixes @mosch's code:
case ARGV.length
when 0
raise "Too few"
when 3..(1.0/0.0)
raise "Too many"
end
You don't have to be Chuck Norris to divide by a floating point zero.
Well, it doesn't work because it's not valid ruby syntax. However, you can do this:
x = 15
case x
when 0..9 then puts "good"
when 10..12 then puts "better"
when 13..200 then puts "best"
else
puts "either great or poor"
end
An if
statement would probably be more fitting for your code, since you don't have a definitive range/value, but rather just a greater-than:
if ARGV.length == 0
abort "Error 1"
elsif ARGV.length > 2
abort "Error 2"
end
You can use either if elsif
or lambda/proc
(then
notation is just for shortness):
case x
when 1 then '1'
when ->(a) { a > 2 } then '>2'
end
You can also create a named variable for clarity:
greater_than_2 = ->(a){ a > 2 }
case x
when 1 then '1'
when greater_than_2 then '>2'
end
You can also create your own comparison predicate:
greater_than = ->(n) { ->(a) {a > n} }
case x
when 1 then '1'
when greater_than[2] then '>2'
when greater_than[5] then '>5'
end
Answering your initial question when > 1
is not a valid syntax, since >
is binary operator in Ruby, which is to say its arity 2, meaning it takes 2 arguments. Don't be confused of term binary vs bitwise.
精彩评论