Hackerrank Ruby - Enumerable - each_with_index Solution
1 min read

Hackerrank Ruby - Enumerable - each_with_index Solution

Hackerrank Ruby - Enumerable - each_with_index Solution

In the previous challenge, we learned about each method being central to all of the methods provided by Enumerable class. One of such useful methods is each_with_index which allows you to iterate over items along with an index keeping count of the item.

For example,> colors = ['red', 'green', 'blue']> colors.each_with_index { |item, index| p "#{index}:#{item}" }"0:red""1:green""2:blue"

As you can note, the counting of items starts from 0.

In this challenge, your task is to complete the skip_animals method that takes an animals array and a skip integer and returns an array of all elements  except first skip number of items as shown in the example below.

For example,> skip_animals(['leopard', 'bear', 'fox', 'wolf'], 2)=> ["2:fox", "3:wolf"]

It is guaranteed that number of items in animals array is greater than the value of skip.

Solution in ruby

Approach 1.

def skip_animals(animals, skip)
    result = []
    animals.each_with_index { |a, i| result << "#{i}:#{a}" if i >= skip }
    result
end

Approach 2.

def skip_animals(animals, skip)
    arr = []
    animals.each_with_index {|animal, i| arr.push("#{i}:#{animal}") if i >= skip}
    arr
end

Approach 3.

def skip_animals(animals, skip)
    rv = []
    animals.each_with_index do |a, i|
        rv << "#{i}:#{a}" if i >= skip
    end
    rv
end

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×