the beauty of ruby 1.9 28. Jun 2008

Let’s say we have a string and three arrays

string = "672"
java = []
ruby18 = []
ruby19 = []

Now you want to convert the string to an array of integers. If you were writing Ruby in javastyle you would probably write something like

i=0
digits = string.split(//)
while i < digits.size do
  java << digits[i].to_i
  i+=1
end

but since we’re we’re doing Ruby in rubystyle it looks more like

string.split(//).each { |digit| ruby18 << digit.to_i }

which looks much nicer, but still not quite right, but with Ruby 1.9’s chars interator it gets even better.

string.chars { |digit| ruby19 << digit.to_i }

Goes down like butter, doesn’t it? Isn’t that how it always should have been? And the good thing is, there is lots of this good stuff in Ruby 1.9. Maybe in Ruby 2.0 there will even be a to_i method in the array class, but now I’m getting carried away.

 

Kommentare (2)

Kommentar schreiben

Markdown Syntax