Skip to content

Instantly share code, notes, and snippets.

@nicohvi
Created June 3, 2016 06:08
Show Gist options
  • Save nicohvi/c703d1adff181150ab2fa21cc5220812 to your computer and use it in GitHub Desktop.
Save nicohvi/c703d1adff181150ab2fa21cc5220812 to your computer and use it in GitHub Desktop.
ruby iteration
test1 = "1\n2\n3"
test2 = [1, 2, 3]
def iterate (obj)
method = obj.is_a?(Array) ? :each : :each_line
obj.send(method) do |line|
yield line
end
end
iterate (test1) do |line|
p line
end
# => 1\n, 2\n, 3\n
iterate (test2) do |line|
p line
end
# => 1, 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment