开发者

Ruby, better way to implement conditional iteration than this?

I have an array @cities = ["Vienna", "Barcelona", "Paris"];

and I am trying to display the individual items with a spacer in between. However it is possible that there is only 1 element in the array, in which case I do not want to display the spacer. And also the array could be empty, in which case I want to display nothing.

For the above array I want the following output:

Vienna
-----
Barcelona
-----
Paris

I use an erb template cityview to apply formatting, css, etc before actually pri开发者_运维问答nting the city names. Simplified, it looks like this:

<p><%= @cities[@city_id] %></p>

I have implemented it as follows...

unless @array.empty?
    @city_id = 0;

    erb :cityview
end

unless @array[1..-1].nil? 
    @array[1..-1].each_index do |i|
        @city_id = i+1;

        puts "<p>-------</p>";

        erb :cityview
    end 
end

Is there a better way?


@cities.join("<p>--------</p>")

Edit to address the template

Here I'm assuming that there's an erbs method that returns the rendered template without doing a puts. Returning the string allows easier manipulation and reuse.

@cities.map { |c| @city = c; erb :cityview }.join("<p>--------</p>")


I'd prefer:

erb:

<p><%= @city %></p>

and loop

@array.each_with_index do |e, i|
    @city = e
    erb :cityview
    puts "<p>-------</p>" if i < @array.length - 1
end

I assume you have split the erb, bit because you want to customize it.


If you want to mix HTML with your city names then you'll need to worry about HTML encoding things before you mix in your HTML. Using just the standard library:

require 'cgi'
html = @cities.map { |c| CGI.escapeHTML(c) }.join('<p>-----</p>')

If you're in Rails, then you can use html_escape from ERB::Util and mark the result as safe-for-HTML with html_safe to avoid having to worry about the encoding in your view:

include ERB::Util
html = @cities.map { |c| html_escape(c) }.join('<p>-----</p>').html_safe


The simpler solution would be to use a spacer template.

http://guides.rubyonrails.org/layouts_and_rendering.html#spacer-templates

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜