Method call confusion

Hi,

I found this method call while following the execution path of a
simple camping project, and I am not sure whether I interpreted it
correctly.

class A
def initialize(options = nil)
@options = options
end
def options
@options ||= {script: 27}
end
end

class B<A
def initialize(*)
super
@lofa = options[:script]
end
end
[4] pry(main)> B.new
=> #<B:0x007f51b1589490 @options={:script=>27}, @lofa=27>

I couldn’t wrap my head around how “options” gets executed when its
definition does not allow any arguments but rewriting it gets the same
results.

[14] pry(main)> A.new.options.
=> 27

Is it this simple or am I missing something else?

regards
attila

This line:

@options ||= {script: 27}

Expands out to something like*:

if @options
  return @options
else
  @options = {script: 27}
  return @options
end

So, the first time you call #options, @options is nil (which is falsy),
so
it gets initialized. Then the second time, it’s already set, so it gets
used directly.

  • actually foo ||= bar expands out to something like: foo || (foo = bar)

On Mon, Jun 2, 2014 at 7:17 AM, Gulyás Attila [email protected]
wrote:

def options
[4] pry(main)> B.new
=> #<B:0x007f51b1589490 @options={:script=>27}, @lofa=27>

I couldn’t wrap my head around how “options” gets executed when its
definition does not allow any arguments but rewriting it gets the same
results.

[14] pry(main)> A.new.options.
=> 27

Is it this simple or am I missing something else?

The way this

@lofa = options[:script]

works is that the parser checks in this scope for an assigment to a
variable called options. It doesn’t find it, so it tags this
occurrence as a method call. When the code is run, the method options
is called with no arguments. Remember that arguments are sent using
parens, not square brackets. The result of that method, then, is sent
the method [] with arguments :script. As has been shown, the result of
the method is either the @options variable if it has been set, or the
hash {:script: 27}.
You can think of the above expression like:

@lofa = options().

Hope this helps,

Jesus.

Ah, sorry, I misunderstood the question.

Yeah, what Jesus said.

On 2 June 2014 17:40, Jesús Gabriel y Galán [email protected]

Then I was on the right track at least. Thanks for both of you!

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