Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created July 2, 2017 17:42
Show Gist options
  • Save oddlyfunctional/195e8910708a8b9b0f19523258d2f61a to your computer and use it in GitHub Desktop.
Save oddlyfunctional/195e8910708a8b9b0f19523258d2f61a to your computer and use it in GitHub Desktop.
Implementando each e select com yield
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
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