1

I have an object named Puzzle and I'm calling .map on it in order to isolate the 'title' values. I then use 'puts' in order to print them neatly but nothing is returned.

def puzzle_find
  title_array = self.puzzles.map { |s| s.title }
  puts title_array
end
#=> " "

If I don't use 'puts' then I get the array like this:

def puzzle_find
  title_array = self.puzzles.map { |s| s.title }
end  

#=> ["title 1", "title 2", "title 3"]

I'm trying to make the output look like this in my view:

title 1
title 2
title 3

thanks

1
  • 1
    The puzzle_find method should not be responsible for printing the array. Just return the array, and handle how you want to display it in the view. Commented Jan 22, 2012 at 20:31

3 Answers 3

3

The collection of titles should be prepared in the controller (or exposed by the controller and retrieved in the model, or etc., as long as there's a collection of titles at the end of it all):

def controller_method
  @puzzles = ... whatever ...
  @titles = @puzzles.collect(&:title)
end 

View:

<% @titles.each do |t| %>
  <%= t %><br/>
<% end %>

(Or wrap it up in a partial, or use a helper. Above assumes scrubbed of HTML badness.)

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

Comments

1
title_array.each do |title|
  puts title
end

Comments

1

Hi When you say "my view", I assume it is html.erb file.

Use join method to insert <br/> into your array:

def puzzle_find
  title_array = self.puzzles.map { |s| s.title }.join('<br/>')
end 

If your "view" is about console outputs:

Use join method with \n:

def puzzle_find
  title_array = self.puzzles.map { |s| s.title }.join('\n')
end  

Example in irb console:

ruby-1.8.7-p334 :001 > puts ["a","b","c"].join("\n")
a
b
c
=> nil 

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.