2

Sorry for this simple question but I am stuck here.

I am trying to create a helper method that simply prints for each object the attribute "name" of my Table "Term".

I tried this:

def display_name(terms)
  terms.each do |term|
    p term.name
  end
end

But instead of printing each objects name, it prints an array for each object with all attributes.

As an example:

[#<Term id: 1, name: "test", definition: "first definition", created_at: "2011-07-21 14:52:12", updated_at: "2011-07-21 14:52:12">, 
 #<Term id: 2, name: "second test", definition: "blabla", created_at: "2011-07-20 18:00:42", updated_at: "2011-07-20 18:04:15">

I am trying to find what I can do with the documentation (content_tag, concat, collect) but it doesn't seem to provide the result I want..

Thanks for your explanation

1 Answer 1

4

The reason for this is because it does not actually print the name, it returns the value from terms.each since that was the last statement in the method.

I would probably use the map method to collect all the names into an array first and if you want a String instead of an Array then I would join them with whatever separator that is preferred, like this:

def display_name(terms)
  terms.map(&:name).join ", "
end

You could also add a parameter to choose the separator if you like. Like this:

def display_name(terms, sep = ", ")
  terms.map(&:name).join sep
end

# in view
display_name(collection, "<br/>")

By default it then uses a comma to separate them but you can manually choose something else.

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

2 Comments

I thought in that case I didn't need to use an array. Thanks a lot it's really clear now!
Note that if performance is a big concern for you &:sym will be quite a bit slower than writing the blocks by hand: m.onkey.org/let-s-start-with-wtf

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.