Frosted MiniColons #
It must have been around revision 1.260 of parse.y that colons came into expression play. And, progressively, colons are getting more airtime in Ruby 1.9. Yet another thing I forgot to mention in What’s Shiny and New in Ruby 1.8.0?
Rather handy for laying out a short if..elsif
series:
unit_of_time = if num < 60: "second" elsif num < 60 * 60: "minute" elsif num < 60 * 60 * 24: "hour" else "day" end
Also, in case..when
:
unit_of_time = case num when 0..60: "second" when 0..60 * 60: "minute" when 0..60 * 60 * 24: "hour" else "day" end
Did you know you can also use keyword then
in place of all the colons above?
And if you want to your colon use to come to a head, try this in Ruby 1.9:
me = {name: "_why", url: "http://redhanded.hobix.com", photo: "http://whytheluckystiff.net/i.home/boy.gif"}
flgr
BTW , you can also do this:
Which I prefer over using long if .. elsif constructs when a regular case statement does not work.
Ben
Do my eyes deceive me, or can Ruby make dictionaries / hashes with the exact same syntax as Python?
why
The colon-hash syntax is a shorthand for hashes with symbols. Quoting the keys will throw an error.
So, instead:
eule
I am all over the new hash syntax. That just rocks.
chris2
Does that work for hashes as final method parameter too?
Adam
On the one hand, I find myself happy to see a keystroke friendly syntax alternative. On the other, I worry about Perl-esque depths of syntactic tyranny: “foo: bar” indicates a key-value pair of a hash on Tuesdays if you’re wearing boxers and the current pope is no more than seven fathers removed from Rasputin. And you hold your tongue just right.
Actually, its not that I think this will happen; I trust Matz to own my brain in a constructive and intuitive way. I just wanted to spread my beautiful characterization of Perl’s syntax rules.
Comments are closed for this entry.