Skip to content

Instantly share code, notes, and snippets.

@vpoola88
Created May 26, 2014 02:46
Show Gist options
  • Save vpoola88/a9b5392e537a6eb49cb4 to your computer and use it in GitHub Desktop.
Save vpoola88/a9b5392e537a6eb49cb4 to your computer and use it in GitHub Desktop.
Add a method named add_index to the Array class. The method should take the index value of an element's position and add it to the String in the same position.
Hint: the each_with_index method should help you solve this problem. Try to find the each_with_index method yourself in Ruby Docs, and learn how it's used.
2.0.0-p353 :001 > class Array
2.0.0-p353 :002?> def add_index
2.0.0-p353 :003?> self.each_with_index do |value, position|
2.0.0-p353 :004 > puts "#{position} is #{value}"
2.0.0-p353 :005?> end
2.0.0-p353 :006?> end
2.0.0-p353 :007?> end
=> nil
2.0.0-p353 :008 > [1,2,3].add_index
0 is 1
1 is 2
2 is 3
=> [1, 2, 3]
2.0.0-p353 :009 > [1,2,3].add_index.join(" ")
0 is 1
1 is 2
2 is 3
=> "1 2 3"
@havenwood
Copy link

result = []
each_with_index { |n, index| result << "#{n} is #{index}" }
result

which you'd actually write:

each_with_index.map { |n, index| "#{n} is #{index}" }

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