Skip to content

def in block argument of Struct.new defines a top-level procedure #1858

@tsahara

Description

@tsahara
Customer = Struct.new(:name, :address) do
  p self
  def greeting
    "Hello!"
  end
end

dave = Customer.new("Dave", "123 Main")
p dave.name     #=> "Dave"
p dave.greeting #=> "Hello Dave!"
p greeting      #=> expected to raise NameError

On CRuby, the last line raises a NameError exception because the method greeting is not defined on top-level (but an accessor of Customer). It is an expected behavior.

#<Class:0x00157a1b98f990>
"Dave"
"Hello!"
a.rb:11:in `<main>': undefined local variable or method `greeting' for main:Object (NameError)

On mruby, it shows "Hello!" and self in the block is not an instance of Customer but main(!):

main
"Dave"
"Hello!"
"Hello!"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions