Peter's Blog

Redefining the Impossible

Ruby Gotcha


Ruby gave me a little puzzle. What gives?

def GetWidgets
  oWidgets = []

  ['a', 'b', 'c'].each { |x|
     oWidgets << x + 'y'
  }
end

This returned

['a', 'b', 'c']

rather than

['ay', 'by', 'cy']

Huh? Well the problem was I forgot to put in return oWidgets at the end. Any stricter language would have complained that I didn't return anything or Python would return None but ruby returned the result of the last expression in the function. This is probably a feature borrowed from perl or php (son of perl) where typing 'return' is a massive strain on the metacarpels.

Still lovin, ruby though. Blocks ftw.


Filed under: noob ruby

Comments are Closed