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!