1

I'm having some problems accessing specific indexes when iterating through a for loop in my view.

The code below is working fine to access the first element, however, I'm getting errors when trying to use the (element) block in place of 0.

@word contains an array of hashes

<!-- loop through word elements -->
<% @word.each do |element|  %>

    <!-- display word -->
    <h1>  <%= @word[0]["word"] %>   </h1>

    <!-- display definition -->
    <p>   <%= @word[0]["text"] %>   </p>

<% end %>

I have a similar loop in my model file which works perfect for returning the array of hashes.

  # create an empty response array for loop below
  response = []

  search.each do |element|
    # Get back the first hash containing word information
    # Without .first returns an array of hashes with multiple definitions for single word
    response << Word.get_definitions(element).first
  end

  # return array of hashes containing information for each word
  return response

Any help is greatly appreciated.

2 Answers 2

3

It sounds like you are treating element as "index in a for loop". element is the actual array element at each iteration. So if an array contains "a", "b", "C" elements then element in array.each do |element| holds "a", "b", "c" respectively on each iteration within the block.

Update your each block to:

<!-- loop through word elements -->
<% @word.each do |element|  %>
    <!-- display word -->
    <h1>  <%= element["word"] %>   </h1>

    <!-- display definition -->
    <p>   <%= element["text"] %>   </p>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure what you holding in @word but you can do try this

<% @word.each do |element|  %>

<!-- display word -->
<h1>  <%= element.word %>   </h1>

<!-- display definition -->
<p>   <%= element.text %>   </p>

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.