Characters and Compatibility

The open_close.rb program is written for Ruby 1.9 and cannot be run in Ruby 1.8. This is because when a single character is returned by Ruby 1.8, it is treated as an integer ASCII value, whereas in Ruby 1.9 it is treated as a one-character string. So, when getc() returns the character, c, Ruby 1.8 is able to test its ASCII value ( c == 10 ), whereas Ruby 1.9 must either test it as a string ( c == " " ) or convert the character to an integer using the ord method: ( c.ord == 10 ). The ord method does not exist in Ruby 1.8.

As a general principle, if you want to write programs that work in different versions of Ruby, you may code around incompatibility issues by testing the value of the RUBY_VERSION constant. This constant returns a string giving a version number such as 1.9.2. You could simply convert the string to a floating-point number using the to_f method and then take different actions if the value is greater than 1.8:

if (RUBY_VERSION.to_f > 1.8) then
    c = c.ord
end

Alternatively, you could analyze the string to determine the minor and major version numbers. Here, for example, is a very simple method that indexes into the RUBY_VERSION string to obtain the first character as the major version ( 1 or 2) and the second character as the minor version (for example, 8 or 9). It returns true if the Ruby version is 1.9 or higher and false otherwise:

open_close2.rb

def isNewRuby
    newR = false # is this > Ruby version 1.8?
    majorNum = RUBY_VERSION[0,1]
    minorNum = RUBY_VERSION[2,1]
    if ( majorNum == "2" ) || (minorNum  == "9" ) then
        newR = true
    else
        newR == false
    end
    return newR
end

You can use this test in your code to deal with compatibility issues. Here the ord method is applied to the character, c, only if the Ruby version is 1.9 or greater:

if (isNewRuby) then
    c = c.ord
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.178.53