Kyle
Kyle

Reputation: 1183

Ruby - For loop with index and element

I'm new to Ruby and am trying to figure out the looping syntax.

I have this pseudocode but need to convert it to Ruby

# array
search = ["fallacy", "epitome"]

for (i = 0, i > search.length, i++) {

  # Get back the result for each search element 
  response[i] = Word.get_definition(search[i])

}

I currently have the following Ruby

# create empty response array
response = []

search.each do |element, index|
    # Get back the result for each search element 
    response(index) = Word.get_definition(element(index))
end

Upvotes: 1

Views: 289

Answers (2)

bjhaid
bjhaid

Reputation: 9752

A more rubyish approach:

response = search.map { |word| Word.get_definition word }

Upvotes: 3

Henrik Andersson
Henrik Andersson

Reputation: 47172

You can skip indices leading to the most straight forward way below

search = ["fallacy", "epitome"]
search.each do |element|
    response << Word.get_definition(element)
end

<< is syntactic sugar for push().

Have you read the documentation for Array or done any tutorials? I could suggest RubyMonk for you.

Upvotes: 3

Related Questions