Ruby - Enumerable - each_with_index

Sort by

recency

|

92 Discussions

|

  • + 0 comments
    First test answer: ["3:panda", "4:tiger", "5:deer"]
    
    def skip_animals(animals, skip)
        animals[skip..-1].each_with_index.map {|v,i| "#{i+skip}:#{v}" }
    end
    
  • + 0 comments
    def skip_animals(animals, skip)
      # Your code here
        animals.enum_for(:each_with_index).select { |v, i| i >= skip }.map { |v, i| "#{i}:#{v}"}
    end
    
  • + 0 comments

    Compiled Answer

    https://github.com/LinaOrmos/Ruby/blob/main/Enumerable%20-%20each%20with%20index%20HackerRank

  • + 0 comments

    The challenge statement, here:

    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.

    doesn't exactly explain what the skip_animals method is supposed to do—you have to return an array of the elements with the indices prefixed like the example shows.

    I've noticed a lot of the Ruby challenges hide parts of the source code from you, and I think it can be useful to see everything that's being run to help learn even more about the language. Luckily, with File.read(__FILE__) we can see the full source code.

    The full source code for this challenge is as follows.

    def skip_animals(animals, skip)
        # Your code here
    end
    
    a1 = ['bat', 'cow', 'jaguar', 'panda', 'tiger', 'deer']
    a2 = ['leopard', 'bear', 'fox', 'wolf', 'dog', 'cat']
    
    def _print_animals(animals, skip)
      animals_ = []
      animals.each_with_index do |item, index|
        next if index < skip
        animals_.push("#{index}:#{item}")
      end
      animals_
    end
    
    user_result1 = skip_animals(a1, 3)
    user_result2 = skip_animals(a2, 0)
    test_result1 = _print_animals(a1, 3)
    test_result2 = _print_animals(a2, 0)
    
    if not (user_result1.is_a? Array and user_result2.is_a? Array)
      puts 'Your method must return an array.'
      exit(0)
    end
    
    if (user_result1 != test_result1) or (user_result2 != test_result2)
      puts 'Wrong! Please check the return value of your program.'
      exit(0)
    end
    
    puts 'Correct! You have a good understanding of Ruby.'
    
  • + 1 comment

    Whats wrong with my code?

    def skip_animals(animals, skip)
      # Your code here
        arr=Array.new
       animals.each_with_index { |item, index| arr.push("#{index+1}:#{item}") if index>=skip } 
        arr
    end