Skip to content

Instantly share code, notes, and snippets.

@citizen428

citizen428/with.rb

Created Mar 21, 2012
Embed
What would you like to do?
ActionScript-like "with" for Ruby, result of SO discussion
module Kernel
def with(obj, &block)
obj.instance_eval &block
obj
end
end
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}"
@padde

This comment has been minimized.

Copy link

@padde padde commented Mar 21, 2012

you could also use @name = … instead of self.name = ...

@citizen428

This comment has been minimized.

Copy link
Owner Author

@citizen428 citizen428 commented Mar 21, 2012

You can, but I prefer using setters/getters over directly manipulating instance vars.

@padde

This comment has been minimized.

Copy link

@padde padde commented Mar 21, 2012

Good point. But it's really interesting that the accessor methods are only available through self, because if you define a method yourself like def hello; puts 'hello!'; end it is available without self. Do you know why?

@citizen428

This comment has been minimized.

Copy link
Owner Author

@citizen428 citizen428 commented Mar 21, 2012

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 body self is the implicit receiver, so the reader works. Now for the writer there's a problem. If you write something like foo = "bar", Ruby will create a new local variable, hence you need to make the receiver explicit. Try defining a method like hello= and you'll see that you'll also need the receiver for the same reason (unless of course you call it like hello=(value)).

@padde

This comment has been minimized.

Copy link

@padde padde commented Mar 21, 2012

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
You can’t perform that action at this time.