Proc&Bloc

Y

Yaya __

Hi
I start learning ruby since a week but i have some probleme to undestand
Proc
and the philosophy which hides behind .
Why don't using methode ?
In this code vhere is the Proc?

def gen_times(factor)
return Proc.new {|n| n*factor }
end

times3 = gen_times(3)
times5 = gen_times(5)

times3.call(12) #=> 36
times5.call(5) #=> 25
times3.call(times5.call(4)) #=> 60

Really it do not arrive to undertand
 
J

John Joyce

Try your code again in irb.
then, in irb
times3.class

Should give you the answer.

Proc

When you def gen_times, actually, you are telling how to create an
instance of Proc with a code block. gen_times's code block happens to
take the factor and multiply it by n
this is like a function object.

If you've only been at it one week, don't worry. It will become clear!
 
Y

Yaya Sow

Hi Thank
I see what is the probleme


irb(main):001:0> def gen_times(factor)
irb(main):002:1> return Proc.new {|n| n*factor }
irb(main):003:1> end
=> nil
irb(main):004:0> times3 = gen_times(3)
=> #<Proc:0x0c373dac@(irb):2>
irb(main):005:0> times5 = gen_times(5)
=> #<Proc:0x0c373dac@(irb):2>
irb(main):006:0> times3.call(12)
=> 36
irb(main):007:0> times5.call(5)
=> 25
irb(main):008:0> times3.call(times5.call(4))
=> 60
irb(main):009:0>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top