irb(main):007:0> [1,3,10,5].each_cons(2).with_object([]){|array,x| array
<< x[1] - x[0]}
NoMethodError: undefined method -' for nil:NilClass from (irb):7:inblock in irb_binding’
from (irb):7:in each' from (irb):7:ineach_cons’
from (irb):7:in with_object' from (irb):7 from C:/Ruby193/bin/irb:12:in’
In the above code I was trying to see which is the perfect “block
argument list” construct. As usual got the error from “Try-I”, but
“Try-II” construct is right.
Now my question is - (A) from the source code, Is there any way to get
the right construct rather blind try. Yes I know that - I should refer
the examples. But in the doc there was several methods for which no
example given. My question is in that case how should be my approach?
(B) How does the array object inside “with_object([])” helping here to
calculate difference? Wanted to know the functional perspective of
"with_object?
Can anyone help me on my question- A. This is a but confusing for me
being a new ruby student?
I have a little difficulty understanding exactly what you’re asking, but
I’ll try to help:
(A) from the source code, Is there any way to get the right construct
rather blind try.
I started by Googling ‘ruby array each_cons’, which lead me to < Module: Enumerable (Ruby 1.9.3)> which says that
each_cons
without a block returns an enumerator. I then searched for ‘ruby
enumerator with_object’ which lead me to < Class: Enumerator (Ruby 1.9.3)>
The method signature for Enumerator#with_object states:
with_object(obj) {|(*args), obj| … }
which tells me straight away that the last block parameter is the
object
I passed to #with_object, and the other args are the elements over which
I’m iterating.
The example given is slightly abstract, as it demonstrates the version
of #with_object without a block argument, but it still shows that:
…with_object(“foo”) {|x,string| puts “#{string}: #{x}” }
outputs
foo: x1
foo: x2
etc.
But in the doc there was several methods for which no example given.
If there is no example, you should read the description. If there is no
description and no example, the simplest thing to do is either: try it
yourself, or come here and ask us.
Poor or missing documentation, especially in the core libraries, is
definitely grounds for filing a bug report.
(A) from the source code, Is there any way to get the right construct
rather blind try.
I started by Googling ‘ruby array each_cons’, which lead me to < Module: Enumerable (Ruby 1.9.3)> which says that
each_cons
without a block returns an enumerator. I then searched for ‘ruby
enumerator with_object’ which lead me to < Class: Enumerator (Ruby 1.9.3)>