Created
March 21, 2012 12:30
-
-
Save citizen428/2146609 to your computer and use it in GitHub Desktop.
ActionScript-like "with" for Ruby, result of SO discussion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Kernel | |
def with(obj, &block) | |
obj.instance_eval &block | |
obj | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Kernel | |
def with(obj, &block) | |
obj.instance_eval &block | |
obj | |
end | |
end | |
class Person | |
attr_accessor :name, :example | |
end | |
tester = with(Person.new) do | |
self.name = "Andy" | |
self.example = "Example" | |
end | |
puts "#{tester.name}:#{tester.example}" |
That makes sense. Thank you very much for explaining this in detail!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only the writers need to be qualified with
self
, not the readers. The reason is simple: when Ruby encounters a bareword, it tries to resolve it as a local var. If there is none, it will try to call a method by that name. Inside the class bodyself
is the implicit receiver, so the reader works. Now for the writer there's a problem. If you write something likefoo = "bar"
, Ruby will create a new local variable, hence you need to make the receiver explicit. Try defining a method likehello=
and you'll see that you'll also need the receiver for the same reason (unless of course you call it likehello=(value)
).