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
end
end
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)}
end
end
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
[/sourcecode]

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.

2 comments:

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!

abrahamezabriskie said...

로고는 ‘블랙잭’이라는 브랜드명을 칼로 휘갈겨 쓴 듯 표현해 힘찬 느낌을 주었고, 해적의 칼인 커틀러스를 부가적인 심벌로 사용했다. 패키지 디자인은 카지노 낡은 느낌의 가죽을 모티브로 했으며, 이것은 해적 의상이나 보물 상자를 연상케 한다. ‘블랙’의 경우는 검은색이 최근 고급 제품을 의미하는 것으로 많이 쓰일 뿐 아니라 해적의 깃발을 연상케 한다는 점도 있다.