-
-
Save aghyad/94f7748fa358b9fefdb6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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