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 == "\n" ) 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 ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.