Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sprintf acting up in 1.9

I am experiencing some confusion on the Kernel#sprintf method in Ruby.

Ruby 1.9 handles encoding in a different way than Ruby 1.8.

Here are the results I am after, and how it behaves in Ruby 1.8:

>> RUBY_VERSION
=> "1.8.7"
>> sprintf("%c", 88599)
=> "\027"

This is how it behaves in Ruby 1.9:

1.9.3p194 :001 > RUBY_VERSION
=> "1.9.3" 
1.9.3p194 :002 > sprintf("%c", 88599)
=> "\u{15A17}"

If I use the magic comment to set the encoding to binary (ascii-8bit) I get an error:

1.9.3p194 :001 > RUBY_VERSION
=> "1.9.3" 
1.9.3p194 :002 > # encoding: binary
1.9.3p194 :003 >   sprintf("%c", 88599)
RangeError: 88599 out of char range
from (irb):3:in `sprintf'
from (irb):3
from /Users/lisinge/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

I have also tried this with Ruby 1.9.2 so there doesn't seem to be specific to 1.9.3.

Maybe I am doing something wrong? I am not so familiar with the Kernel#sprintf method.

I am using a smpp library called ruby-smpp which can be found on github. It is the send_concat_mt method on line #47 that is acting up when i am trying to run it in Ruby 1.9.3.

I would greatly appreciate it if any of you could shed some light on this matter.

like image 202
Lisinge Avatar asked Nov 13 '22 03:11

Lisinge


1 Answers

The sprintf documentation states:

Field |  Other Format 
------+--------------------------------------------------------------
  c   | Argument is the numeric code for a single character or
      | a single character string itself.

88599 is not a valid numeric code for a single character in the default behavior for Ruby 1.8; which, I believe, is no encoding. What it appears to be doing is doing a mod 256 on the value you supply and then converting it:

% irb
1.9.3-p194 :003 > 88599 % 256 == 027
 => true 

As to you doing something wrong, no. What did happen is that allowing out-of-bounds character codes was a bug that has been fixed by Ruby 1.9 which now properly throws an exception.

like image 106
Lee Avatar answered Dec 02 '22 13:12

Lee