Tuesday, May 27, 2008

Syntactic Sugar...

Was reading this post about Groovy syntactic sugar... closures and ++ operator are nice... but you could open up Hash and Array to get the other stuff.

[sourcecode language="ruby"]
# working with hashes
class Hash
def method_missing(name, *args)
fetch(name) if has_key?(name) or nil
user = {:save => true, :destroy => false}
puts "--hashes"
puts "save? : #{user.save}"
puts "destroy? : #{user.destroy}"

# working with arrays
class Array
def method_missing(name, *args)
collect {|i| i.send(name)}
puts "--upcase"
puts ["Mike", "McKinney"].upcase

# fetching attributes of arrays
name1 = {:first_name => "Mike", :last_name => "McKinney"}
name2 = {:first_name => "Bo", :last_name => "Diddley"}
names = [name1, name2]

puts "--first names "
puts names.first_name
puts "--last names "
puts names.last_name
puts "--middle names "
puts names.middle_name

Of course you would want to look a little closer at the implications this type of patch would have on your code, but it's sure nice how flexible ruby can be.

1 comment:

Matt Harrah said...

I know you're a big fan of Ruby, Mike, and rightly so. You also know how hesitant I have been to make the dynlang leap. Interesting that you mention Groovy, because I've been playing with it a little recently and I really like what I see. And it is definitely loaded with syntactic sugar. I'm usually not a big fan of syntactic sugar, but with expressivity being a key concern for dynlangs, I am surprisingly accepting of it in Groovy (and to a lesser degree Ruby which I don't know very well, but I've liked what I've seen).

Good article!