Skip to content

Instantly share code, notes, and snippets.

@randalmaile
Last active January 2, 2016 08:49
Show Gist options
  • Save randalmaile/8278575 to your computer and use it in GitHub Desktop.
Save randalmaile/8278575 to your computer and use it in GitHub Desktop.
Blocks, Procs and Lambdas
1. scope :public_vis, lambda { where(public: false)}
...AND
scope :public_vis, -> { where(public: false) } do the same thing!
is -> the same thing as the lambda key word???
1. Blocks - seen it dozens of times:
a. Basic
``` a = [1,2,3]
a.map! do |n|
n**2
end
=> [1,4,9]
"Sending the map! method to an array instance with a block of code
```
b. Yield
```
class Array
def iterate!
self.each_with_index do |n, i|
self[i] = yield(n)
end
end
end
array = [1, 2, 3, 4]
array.iterate! do |n|
n ** 2
end
"The yield here is evaluating the passed in block, and if there are any arguments, they are passed into the block, then the return value is set to the array element w/ given index - cool!"
c. Using &block
class Array
def iterate!(&block)
self.each_with_index do |n, i|
self[i] = block.call(n)
end
end
end
array = [1, 2, 3, 4]
array.iterate! do |n|
n ** 2
end
"Very similar to yield, except that the iterate method is taking in the block as a param and within the iterator, it's being called w/ the keyword "call" the passed in value(n)"
c.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment