hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Frosted MiniColons #

by why in inspect

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"}
said on 07 Feb 2005 at 15:52

BTW , you can also do this:

unit_of_time = case
  when num < 60:           "second" 
  when num < 60 * 60:      "minute" 
  when num < 60 * 60 * 24: "hour" 
  else                     "day" 
end

Which I prefer over using long if .. elsif constructs when a regular case statement does not work.

said on 07 Feb 2005 at 15:59

Do my eyes deceive me, or can Ruby make dictionaries / hashes with the exact same syntax as Python?

said on 07 Feb 2005 at 16:14

The colon-hash syntax is a shorthand for hashes with symbols. Quoting the keys will throw an error.

So, instead:

 >> tel = {jack: 4098, sape: 4139}
 >> tel[:guido] = 4127
 >> tel
 => {:sape => 4139, :guido => 4127, :jack => 4098}
 >> tel[:jack]
 => 4098
 >> tel.delete :sape
 => 4139
 >> tel[:irv] = 4127
 >> tel
 => {:guido => 4127, :irv => 4127, :jack => 4098}
 >> tel.keys()
 [:guido, :irv, :jack]
 >> tel.has_key? :guido
 => true
said on 08 Feb 2005 at 02:09

I am all over the new hash syntax. That just rocks.

said on 08 Feb 2005 at 08:16

Does that work for hashes as final method parameter too?

said on 08 Feb 2005 at 20:42

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.