Crystal: No way to set an attribute from a block called via `with self yield`

Created on 22 Apr 2017  路  5Comments  路  Source: crystal-lang/crystal

class A
  property attr = 0

  def config
    with self yield
    self
  end

  # other methods
end

a = A.new.config do

  # How do I set A#attr from here ?
  #----------------------------------
  # attr = 42           will create a local variable
  # self.attr = 42      errors with: there's no self in this scope

end

puts a.attr # I want 42!

https://carc.in/#/r/1wta

Most helpful comment

Well , 42 is the ultimate question to life , the universe and everything else , so it might take a lot of ram to calculate ;)

All 5 comments

No no way. You can use itself instead of self.

class A
  property attr = 0

  def config
    with self yield
    self
  end

  # other methods
end

a = A.new.config do
  itself.attr = 42
end

puts a.attr # I want 42!

(itself is Object method to return self. doc is here.)

https://carc.in/#/r/1wun

If you use @attr = 42 there, compiler program will eat infinite memory, looks like a bug. https://carc.in/#/r/1wuo

Well , 42 is the ultimate question to life , the universe and everything else , so it might take a lot of ram to calculate ;)

@bararchy Wow!

I think this problem is not related in this issue because it can be simplified to:

def foo
  yield
end

foo do
  @foo = 1
end

It is quite a bug.

@MakeNowJust didn't know the itself trick, thanks! And nice bugfix 馃槃

Was this page helpful?
0 / 5 - 0 ratings