Pergunta

I am using Ruby 2.1.1 and I have faced with strange behavior of the ruby block inside of the ternary operator. Please consider the following program:

module Prawn 
  class Document
    def self.generate(filename, &block)
      block.arity < 1 ? instance_eval(&block) : block[self] 
      p '---'
      block[self]
    end
  end
end

class A
  def initialize
    @a = 1
  end

  def foo
    qwe = 1
    Prawn::Document.generate("foobar") do 
      p @a
      p qwe
      p instance_variables  
    end
  end
end

A.new.foo

The thing, which is confusing me is Output of this program:

nil
1
[]
"---"
1
1
[:@a]

Can someone explain me why the results above the "---" are differ from the results below the "---"?

Foi útil?

Solução

It has nothing to do with the ternary operator. The arity is 0, which is less than 1, so you're comparing instance_eval(&block) (apples) and block[self] (oranges). You'd get the same result if you did

def self.generate(filename, &block)
  instance_eval(&block)
  p '---'
  block[self]
end

And the difference is easy to understand: the former is evaluated with self being a Prawn::Document class object, and in the latter, self is an instance of A.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top