This works:
language_name = "C"
case language_name
when "C"
puts "The language is C."
when "Rexx"
puts "The language is Rexx."
else
puts "The language is unknown"
end
So does this:
case language_name
when "C"
begin
puts "The language is C."
end
when "Rexx"
begin
puts "The language is Rexx."
end
else
begin
puts "The language is unknown."
end
end
But this gives a syntax error:
case language_name
when "C"
do
puts "The language is C."
end
when "Rexx"
do
puts "The language is Rexx."
end
else
do
puts "The language is unknown."
end
end
Why? Nowhere I looked seemed to help. What am I missing?
I know do/end isn't necessary, but why does it fail?
Thanks.
on 2012-12-28 02:54
on 2012-12-28 03:09
Paul, the "begin ... end" syntax is meant for exception handling. For example, you can use it like this: begin a = 1/0 rescue ZeroDivisionError puts "You tried to divide by zero!" end The "do ... end" syntax is used for blocks. The "when" part in a case statement doesn't accept a block argument (it's not even a method), so it is a syntax error. ----- Carlos Agarie Control engineering Polytechnic School, University of So Paulo, Brazil Computer engineering Embry-Riddle Aeronautical University, USA 2012/12/27 Paul Magnussen <lists@ruby-forum.com>
on 2012-12-28 03:11
begin puts "The language is C." end --output:-- The language is C do puts "The language is C." end --output:-- 1.rb:1: syntax error, unexpected keyword_do_block 1.rb:3: syntax error, unexpected keyword_end, expecting $end
on 2012-12-28 14:32
Thank you both. Carlos, where is this information (about 'when' not accepting a block) on the 'Net, please? I'm afraid I couldn't find it, although I looked at ruby-lang.org and several other places.
on 2012-12-28 15:20
> Carlos, where is this information (about 'when' not accepting a block) > on the 'Net, please? I'm afraid I couldn't find it, although I looked > at ruby-lang.org and several other places. Well you have to think out that every code inside "when" and the next "when" ;or between "when" and "else";or between "when" and "end";or between "else" and "end" is a chunk of code, so it's like a block, you don't need to put the code inside "do .. end" or {}. It is not necesary, of course you can use blocks inside for example: a = 1 b = ["one", "two"] case a when 0 b.each do │number│ number.capitalize! end else begin a.length rescue => e puts "The error is #{e}" end end This will finish with an error, and I maked that with the purpose to show in which case you can use "begin .. end", if you don't want to rescue nothing is not necesary use "begin .. end", just put the chunk of code. Well hope this help you, see ya' :)
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.