RubyNation: Preparing for 1.9

David A Black — Preparing for 1.9

“open a 1.8.6 [irb] and you’ll see all the stuff I’m showing you not work”

David showed us some of the differences between the 1.9 and 1.8.6 with live code demos.

generic to_a gone. I’d seen it in the docs for 1.8.6, but never used it. It doesn’t make sense for a number to know how to wrap itself in an array. Seeing it go makes me happy.


String no longer mixes in Enumerable. Instead of each, et al it has new each_* methods.

  • each_byte –again duh
  • each_char — duh
  • each_checkpoint — gives you the bits for the would be character regardless of encoding
  • each_line –duh
# 1.9
#=> "s"
#=> 115

str[0] returns a string of length one rather than a Fixnum representing the nth byte as 1.8.6 does. To get the same behavior in 1.8.6 you need to write str[0,1] which is not at all intuitive. I had run into that a few times and always thought it was odd for a language with such an awesome string manipulation toolkit to do.

case statements no longer have the optional ‘:’. when x: blah won’t work, it will have to be when x; blah

rubygems now part of core, so no need to require ‘rubygems’ before requiring a gem. Sweet.

{1,2,3,4} does not turn into {1=>2,3=>4} you always need the hashrockets(=>).

Also, hashes retain insertion order so you can now rely on what use to be coincidental. Cool. This also means that you can use position as well as key to refer to values…which confuses me because hashes can have numeric keys.ruby

Block local variables(let () anyone?). done like so

local_var = 'something to not overwrite'
do |a;local_var|
  local_var = cool_intermediate_method a
  some_method local_var
# local_var == 'something to not overwrite'

String encoding got some smarts. Ruby knows more about how to deal with string encoding in 1.9. David showed us some examples. If you change a string to ASCII and then try to add a Unicode character to it, the system will convert the string’s encoding to Unicode first.

Like java iterators, only with more awesome. Apparently, these have been around for a while(1.8.7), but I hadn’t used them before. You can do cool stuff like:

e = (1..3).cycle
e.take 5
 #=> [1, 2, 3, 1, 2]
e2 = e.each_slice 2
e2.take 5
  #=> [[1, 2], [3, 1], [2, 3], [1, 2], [3, 1]]
e3 = e.each_cons(2)
e3.take 5
  #=> [[1, 2], [2, 3], [3, 1], [1, 2], [2, 3]]

Then there is the new BasicObject. It is like Jim Weirich’s BlankSlate, but baked in. Objects with no default methods are really handy for building DSLs, like builder.

a =
p a
#=> NoMethodError: undefined method `inspect' for #<0x8441f94>