From: "David A. Black" Date: 2009-07-21T06:30:52+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: > brabuhr@gmail.com wrote: >>> 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" >> :-) > > That seems like a pretty good approach, actually, and it happens to be what > the snmp gem does (lib/ber.rb): > > # > # Add ord method to Fixnum for forward compatibility with Ruby 1.9 > # > if "a"[0].kind_of? Fixnum > unless Fixnum.methods.include? :ord > class Fixnum > def ord; self; end > end > end > end There's always a bit of fragility, since someone else might have added an ord that does something else... unlikely, of course, but still. Also, I didn't suggest adding String#ord because you had said you didn't want to add methods to String (though your next post clarifies what you meant by that). If you want to be more future-esque you could add it to String instead of Fixnum (though that might involve one of those unpack-based implementations and therefore not be as fast). 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)