Ruby 1.9 Encoding Fun

Ruby 1.9 has a great support for encoding, this post covers that for a big deal, however with this support out of the box, things like this becomes easier, just note the source code is not limited to few types of encoding just like Ruby 1.8.

# coding: UTF-8
 
π = Math::PI
 
def(x) 
  Math.sqrt(x)
end
 
def(r)
  r.inject{|sum,val| sum + (block_given? ? yield(val) : val)}
end 
 
def(r)
  r.inject(1){|mul,val| mul * (block_given? ? yield(val) : val)}
end 
 
def ¬(x)
  !x
end	
 
p π #=> 3.14159265358979
 
p(9) #=> 3.0
 
range = 1..6 
 
p(range)  #=> 21
 
p(range){|x| x**2}  #=> 91
 
p(range)  #=> 720
 
p(range){|x| x**2}  #=> 518400
 
p ¬(5>0) #=> false

Please note that previous example could work also with Ruby 1.8 using the flag -Ku, I just wanted to explain the idea of using different types of encoding in Ruby 1.9.

So all you need to do is to set whatever encoding you want for your source code at the very beginning of the file:

# coding: UTF-8

Many other things can be done, just give yourself a moment and think what you can do!

This entry was posted in Ruby and tagged , , . Bookmark the permalink.

4 Responses to Ruby 1.9 Encoding Fun

  1. Moski says:

    This is really cool, i luv it

  2. Francky says:

    very usefull and human!!

  3. El Cy says:

    So Ruby is “stealing” from Scala now ;) … Nice cross-polination !

  4. Buck says:

    Now I can run the code examples from Alonzo Church’s text on the Lambda Calculus, verbatim. Sweet! 8)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">