Hi,
The following statement will generate a syntax error:
text.gsub!(/&#(\d+);/) do begin $1.to_i.chr rescue end; end
also, this is wrong:
text.gsub!(/&#(\d+);/) do $1.to_i.chr rescue end
but this is ok:
text.gsub!(/&#(\d+);/) do
begin
$1.to_i.chr
rescue
end;
end
Can anyone explain to me the general rules of when I can write code on
one line, and when I must write it on multiple lines?
Thanks!
Shannon
text.gsub!(/&#(\d+);/) do
begin
$1.to_i.chr
rescue
end;
end
Can anyone explain to me the general rules of when I can write code on
one line, and when I must write it on multiple lines?
I would trust that (\d+) will succesfully turn into an integer and forget
exception handling:
text.gsub!(!(/&#(\d+);/) { $1.to_i }
I don’t know what you could possibly have to rescue, anyway, because $1 will
always be a string in that context, so #to_i will succeed.
As a matter of style, I never use do … end on a single line. I use do …
end for “procedures” (i.e. do something) and { … } for evaluation purposes.
Sorry to not answer your question fully, but hopefully this will help a bit.
Gavin
···
From: “Shannon Fang” xrfang@hotmail.com [snipped]
Shannon Fang xrfang@hotmail.com writes:
Hi,
The following statement will generate a syntax error:
text.gsub!(/&#(\d+);/) do begin $1.to_i.chr rescue end; end
You just have to put more semicolons in at the end of statements:
text.gsub!(/&#(\d+);/) do begin $1.to_i.chr; rescue; end; end
Can anyone explain to me the general rules of when I can write code
on one line, and when I must write it on multiple lines?
Maybe “statements are terminated by an end of line or a semicolon.”
Ruby’s syntax is not “whitespace insensitive” like many other
languages, but it is generally intuitive – especially when not trying
to cram too much onto one line. 