play with Symbol#to_proc English Posting

If you are reasonable rails developer, you are so familiar with " &:symbol ". Have you thought how it work?

Start with '&' operator. If you pass something with '&' to method, ruby think the something is a Proc object. However, when it isn't Proc object, ruby call to_proc method of the something to get Proc object. Let's see example code.
class Mine
end

def method(&block)
end

m = Mine.new
method(&m)
When you run above code, you will get error message: wrong argument type Mine (expected Proc) (TypeError)

Ok. Modify it.
class Mine
  def to_proc
    Proc.new { puts "Wow" }
  end
end

def method(&block)
  block.call
end

m = Mine.new
method(&m)
The running result is : Wow.

Yeah. Same effect is happened in Symbol class.
class Terminator
  def who_am_i
    puts "I'm a machine!! I'll be back!!"
  end
 
  def order(&block)
    block.call self
  end
end

t100 = Terminator.new
t100.order(&:who_am_i)
The result is : I'm a machine!! I'll be back!!

Symbol#to_proc method return like as:
Proc.new { |obj, *args| obj.send(self, *args) }
so when you pass &:who_am_i, it works like t100.send(:who_am_i) and it same as t100.who_am_i.

Unfortunately, until ruby 1.8.6 doesn't have to_proc method in Symbol class, so rails defined to_proc in Symbol class. You can find it in 'activesupport-2.1.1/lib/active_support/core_ext/symbol.rb'. So if you want to use &:symbol in ruby(not in rails) that version is earlier than 1.8.7, you should define to_proc your self.

However, the Symbol#to_proc was included since 1.8.7, so you can use it without define it yourself.

Finally, let's dig to 'activesupport-2.1.1/lib/active_support/core_ext/enumerable.rb'. You can see sum method in the file like below:
def sum(identity = 0, &block)
  return identity unless size > 0

  if block_given?
    map(&block).sum
  else
    inject { |sum, element| sum + element }
  end
end
Above code and Symbol#to_proc method make our life is easyer and butiful. It's so great, isn't it?

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://classpath.egloos.com/tb/4686599 [도움말]

덧글

덧글 입력 영역


구글애드센스