Sunday, June 17, 2012

to_proc working magic

I had an interesting puzzle in ruby to capitalize words with in a string.
text = "this is an interesting blog post about to_proc"

text.split.map(&:capitalize).join ' '

# "This Is An Interesting Blog Post About To_proc" 

Just was nailing down the answer I got, with the internals wired.
Normally single argument block comes after a map like this,
{ |arg| arg.capitalize! }

But how does ruby allows us to use syntactic sugar coated pill like passing a symbol to a map?
Explanation can be found here, symbol to_proc.
Need to smell some samples & create your own version of it? Here below...
class MyString < String

  def double
    self * 2
  end

  def triple
    self * 3
  end

  def map_char(&p)
    result = []
    self.each_char do |c| 
      result << p.call(c)
    end
    result.join
  end

end


name = MyString.new("hariharan")

#usual way
p name.map_char { |m| m * 2} # "hhaarriihhaarraann" 

#syntactic sugar coated pill
p name.map_char(&:triple) # hhhaaarrriiihhhaaarrraaannn

On whole, the mist here is class 'Symbol' has a to_proc method, that accepts  object  as an argument and passes the message of 'symbol' to that object.

Stay tuned for my next blog about scala magic sugar coated stuff...

No comments: