How does the expression ] work in Ruby?

Hi,

*a…b means, it will apply the method Enumerable#to_a method on the
Range
instance a…b.

Baiscally [*2…6] is same as (2…6).to_a.

Now I wanted to confirm myself, if I am correct it or not. Thus I did
check it
from the below code.

trace = TracePoint.new do |tp|
p [tp.lineno, tp.event, tp.defined_class,tp.method_id]
end

trace.enable do
[*2…6]
end

>> [5, :b_call, nil, nil]

>> [6, :line, nil, nil]

>> [6, :c_call, Enumerable, :to_a]

>> [6, :c_call, Range, :each]

>> [6, :c_return, Range, :each]

>> [6, :c_return, Enumerable, :to_a]

>> [7, :b_return, nil, nil]

The code is showing yes, #to_a method got called. But don’t know why
Range#each method invoked. Can anybody give me some light on this ?
How does
#each involved in this range object destruction
?

Regards,
Arup R.

Debugging is twice as hard as writing the code in the first place.
Therefore,
if you write the code as cleverly as possible, you are, by definition,
not
smart enough to debug it.

–Brian Kernighan

Enumerable#to_a uses #each internal that is defined in Range
how else should it make an Array?

macro substitution or polymorphic interface if you will -> [*2…6] looks
like it’s an array that calls enum_for/each reaches the enum star
(splat)
call on range which then yields the range back into enum_for/each for
array
coercion which is finally yielded back as the expanded array in
uncompressed form … when it’s working through it the ranges to_a it’s
really just expanding to: 2.upto( 6)

=P

Now if ruby allowed lambda to be the (arg . body) of a def we could have
a
even more fun! Then again writing our own defn probably wouldn’t be
terribly difficult.

~Stu

On Wed, Jun 4, 2014 at 9:37 AM, Arup R.
[email protected]

On 5 June 2014 11:53, Stu [email protected] wrote:

Now if ruby allowed lambda to be the (arg . body) of a def we could have a
even more fun! Then again writing our own defn probably wouldn’t be
terribly difficult.

irb(main):001:0> RUBY_VERSION
=> “1.9.3”
irb(main):002:0> class Foo; end
=> nil
irb(main):003:0> sheep = -> { ‘bah bah bah!’ }
=> #<Proc:[email protected](irb):3 (lambda)>
irb(main):004:0> Foo.send :define_method, :bar, &sheep
=> #<Proc:[email protected](irb):3 (lambda)>
irb(main):005:0> Foo.new.bar
=> “bah bah bah!”

Also works in 2.2.0 (trunk), and everywhere in between. :wink:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs