Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array#to_proc
## Like a Symbol#to_proc but for array
class Array
def to_proc
lambda {|object|
self.map{|symbol| object.send(symbol.to_sym)}
}
end
end
## Some class
class Person
attr_accessor :id, :name
def initialize()
@id = 1
@name = 'John'
end
end
## Usage
crowd = []
5.times{ crowd << Person.new }
puts crowd.collect(&[:id, :name]).inspect
puts crowd.collect(&['name', 'id']).inspect
=>
[[1, "John"], [1, "John"], [1, "John"], [1, "John"], [1, "John"]]
[["John", 1], ["John", 1], ["John", 1], ["John", 1], ["John", 1]]
## A different implementation that empower you to call symbol#to_proc method with parameters
# http://www.sanityinc.com/articles/adding-array-to-proc-to-ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment