Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Simon Ask Ulsnes

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

With object do...

This code enters the scope of an object, so you can temporarily avoid having to reference it by name.

Effectively changes the value of 'self' in the block scope. This also enables you to run private methods on the object without using __send__.

def with(object, &block)
    object.instance_eval(&block)
end


Example of usage:
numbers = [1, 2, 3]

with numbers do
	map! { |n| n + 100 }
	reject! { |n| n % 2 == 0}
end

p numbers # => [101, 103]

n = 15
n = with n do
    self + 13
end
p n # => 28


This gets much more interesting with complex objects that have lots of attributes and you want strict control over how they're set.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS