Created
July 2, 2017 17:42
-
-
Save oddlyfunctional/195e8910708a8b9b0f19523258d2f61a to your computer and use it in GitHub Desktop.
Implementando each e select com yield
This file contains hidden or 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
global: | |
| each|... | |
| select|... | |
| | |
| prog.rb: | |
| | pares|nil | |
| | | |
| | |
| select: | |
| | array|[1, 2, 3, 4] | |
| | vencedores = [2, 4] | |
| | | |
| | bloco dentro do select: | |
| | | item|2 | |
| | | | |
| | | |
| | |
| | |
| bloco dentro do prog.rb: | |
| | i|2 | |
| | | |
| | |
Output: | |
[2, 4] | |
Blocos | Métodos | |
não tem return | tem return | |
não precisam saber o nome | precisa saber o nome | |
estão dentro do escopo em que foi CRIADO | não sabe nada do escopo em que foi criado |
This file contains hidden or 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
def each(array) | |
i = 0 | |
while i < array.length | |
item = array[i] | |
yield(item) | |
i += 1 | |
end | |
end | |
def select(array) | |
vencedores = [] | |
each([1, 2, 3, 4]) do |item| | |
if yield(item) | |
vencedores << item | |
end | |
end | |
vencedores | |
end | |
pares = select([1, 2, 3, 4]) { |i| i.even? } | |
p pares |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment