1

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
1
  • 1
    if you truely need the index you can use search.index(element) but @limelights solution seems to fit your needs. Commented Dec 23, 2013 at 20:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

A more rubyish approach:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.