Skip to content

Instantly share code, notes, and snippets.

@aghyad
Forked from shell/core_exts.rb
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aghyad/94f7748fa358b9fefdb6 to your computer and use it in GitHub Desktop.
Save aghyad/94f7748fa358b9fefdb6 to your computer and use it in GitHub Desktop.
## 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