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-3 of 3 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.

In-place map_with_index

// This code is similar to Enumerable#map, but like each_with_index, it also yields the index of the current element.

class Array
    def map_with_index!
       each_with_index do |e, idx| self[idx] = yield(e, idx); end
    end

    def map_with_index(&block)
        dup.map_with_index!(&block)
    end
end

Map array to hash, with custom key and value

This code creates a hash from an array, using a block to determine the keys and values of the hash.

class Array
	def map_to_hash
		map { |e| yield e }.inject({}) { |carry, e| carry.merge! e }
	end
end


Use like this:
[1, 2, 3].map_to_hash { |e| {e => e + 100} } # => {1 => 101, 2 => 102, 3 => 103}
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS