Skip to content

Instantly share code, notes, and snippets.

@ralphos
Created April 30, 2012 02:22
Show Gist options
  • Save ralphos/2554968 to your computer and use it in GitHub Desktop.
Save ralphos/2554968 to your computer and use it in GitHub Desktop.
tmp.rb
s = "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n"
def add_index(lines)
indexed_lines = []
lines.each_line.each_with_index do |line, index|
indexed_lines << "Line #{index + 1}: #{line}"
end
indexed_lines
end
lines = add_index(s)
lines.each { |line| puts line }
@kotp
Copy link

kotp commented Apr 30, 2012

Should probably be each_line.with_index

@ralphos
Copy link
Author

ralphos commented Apr 30, 2012

You're right. I checked out the .with_index method and applied it below with an offset value.

s = "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n"

def add_index(lines)
  indexed_lines = []
  lines.each_line.with_index(offset = 1) do |line, index|
    indexed_lines << "Line #{index}: #{line}"
  end
  indexed_lines
end

lines = add_index(s)
lines.each { |line| puts line }

@kotp
Copy link

kotp commented May 1, 2012

s = "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n"

def add_index(lines)
  indexed_lines = []
  lines.each_line.with_index(1) do |line, index|
    indexed_lines << "Line #{index}: #{line}"
  end
  indexed_lines
end

lines = add_index(s)
lines.each { |line| puts line }

The offset = 1 inside of the method call doesn't make sense. It is assigned, but not available anywhere outside of the method, and is not used anywhere in your add_index() method at all. The value it returns of 1 is used though. So it is better just to give the value of one. It does have the effect of documenting what the value is, but once it is understood what the value is intended for, it is unnecessary and unused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment