From: "David A. Black" Date: 2009-07-21T04:08:58+09:00 Subject: Re: getting char from string as fixnum in 1.8 and 1.9 Hi -- On Tue, 21 Jul 2009, 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 I'm sure someone will have something more elegant but I'll get the ball rolling with: def third_char_as_fixnum(s) s[2,1].unpack("C*")[0] end It may not pass the not losing much efficiency test, though. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN)