0

I'm trying to insert a object into a array, but instead of insert into array, it prints in the screen the memory addresses.

I have the following code in my controller:

@article = Article.new("test","test1")
@articles <<  @article     #this line causes the prints

And my view have this code:

<%=
    @articles.each do |a|
    a.titulo + " / " + a.texto
    end
%>  

4 Answers 4

3

Your problem is with how you render the @articles:

<%= @articles.each do |a| a.titulo + " / " + a.texto end %>

The return value of each is the array itself. You want to render each element within the array, so you should do something like this:

<% @articles.each do |a| %> 
  <%= a.titulo + " / " + a.texto %>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

1

You could force @articles to be an array like this:

@articles ||= []

Then add your @article like you were already doing

1 Comment

Good call. Edited answer.
1

Create @articles as an Array before adding to it with <<.

E.g.,

class MyController < ...
  def your_method
    @articles ||= []
    @article = Article.new("test","test1")
    @articles <<  @article
  end

  ...
end

(and/or in a before_ filter and/or...)

2 Comments

Having an initialize in a controller is not very idiomatic, I don't recommend it. Instead, I recommend a private method: def articles; @articles ||= []; end;
Yeah, initialize in a controller is going to cause problems. Don't do this. Instead use a before_filter.
1

This is likely expected behavior. If @articles is indeed an array, this should work. Just check the array after the append and make sure the newly added element is there. If you are doing this from the console, then the printing you are seeing is probably console behavior and not << behavior.

Because of the comment below, I'm changing my answer to reflect the actual problem. You are trying to render the enumerator to the view, and not the articles. Your view should look like:

<% @articles.each |a| %>
  <%= a.titulo + " / " + a.texto %>
<% end %>

5 Comments

Thanks for answer. I am running it in web, its prints the memory addresses in the web page.
How exactly are you printing it to the page?
I am doing this in the view to show the results <%= @articles.each do |a| a.titulo + " / " + a.texto end %>
@Afaria - you should add this to your post - your problem is here, not where you think it is...
I believe that is your problem. You are trying to render the enumerator to the view, not the articles themselves. You should be doing it something like: <% @articles.each do |a| %> <%= a.titulo + " / " + a.texto %> <% end %>

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.