From: brabuhr@... Date: 2009-07-21T05:26:45+09:00 Subject: Re: getting char from string as fixnum in 1.8 and 1.9 On Mon, Jul 20, 2009 at 7:40 PM, Glenn Jackman wrote: > At 2009-07-20 02:20PM, "Joel VanderWerf" wrote: >> >>  What's the best way to write this program so that it will run correctly >>  on both 1.8 and 1.9? This works, but I'm just curious if there's >>  anything better, preferably without the RUBY_VERSION test, without >>  adding methods to String, and without losing much efficiency compared >>  with 1.8's String#[]. >> >>  if RUBY_VERSION =~ /\A1\.9/ >>     def third_char_as_fixnum(s) >>       s[2].ord >>     end >>  else >>     def third_char_as_fixnum(s) >>       s[2] >>     end >>  end >> >>  s = "abc" >>  p third_char_as_fixnum(s) # ==> 99 > > This works in both 1.9.1 and 1.8.7 > >     def third_char_as_fixnum(s) >       s[2].ord >     end > > Because Integer#ord returns the integer receiver. > ruby -v -e 'p "foo"[2].ord' ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-linux] -e:1: undefined method `ord' for 111:Fixnum (NoMethodError) > cat foo.rb unless 0.respond_to?(:ord) class Integer def ord; self; end end end > ruby -v -rfoo -e 'p "foo"[2].ord' ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-linux] 111 Still meets the constraint: "without adding methods to String" :-)