Ruby - Enumerable - each_with_index

  • + 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.'