Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Jean Malan
Jean Malan
10,781 Points

How to run a loop equal to the size and value of an array.

The Input of the @behaviour will be a something like LMLMLM which will be stored in an Array ["L", "M", "L", "M", "L", "M"]. I want to run the if statements in the rover_behaviour to all of the characters in the array. So if it is LMLMLM - it will run the if statement 6 times to each of the characters. I just have no idea how to run that loop?

def rover_behaviour
 puts " \n Please input the behaviour of the rover(L,R & M):    "
 input = gets.chomp.upcase
 @behaviour = input.scan /\w/

  if @behaviour[0] == "L" 
    move_left

  else if
  @behaviour[0] == "R" 
  move_right

  else if
  @behaviour[0] == "M"
    move_forward

  end
  end
  end
end

1 Answer

Britton Baumann
Britton Baumann
10,495 Points

You can use an each method to iterate over an array in ruby. So you could do something like this

@behaviour.each do |item|
  if item == "L"
      move_left

  elsif item == "R"
    move_right
  elsif item == "M"
     move_forward
  else
     hold_position
  end
end

The each method will go through each item in the array and then you can compare the items however you need. Here is a video explaining it on teamtreehouse. https://teamtreehouse.com/library/iteration-with-each