开发者

Using to_sentence

开发者 https://www.devze.com 2023-02-03 20:39 出处:网络
I\'m a newbie... I know how to use \"to_sentence\" when I have something like: <%= @blah.collect {|b| b.name}.to_sentence %>

I'm a newbie...

I know how to use "to_sentence" when I have something like:

<%= @blah.collect {|b| b.name}.to_sentence %>

but what if I have a more complex block like:

<% skill.position.each do |position| %>              
  <a href="<%= position.company.url %>"><%= position.company.name %></a>
  <% if position.salary? %>
    <span><%= position.salary %></s开发者_开发问答pan>
  <% end %>
<% end %>

The desired output is:

Microsoft, Google 2000, and Yahoo.


Couldn't you just collect it without .each?

<%= skill.positions.collect{ |p| "<a href=\"#{p.company.url}\">#{p.company.name}</a>#{position.salary? ? '<span>#{position.salary}</span>' : nil}" }.to_sentence %>

That should work for you...

You could also do this:

<%= skill.position.each do |position| %>              
  <a href="<% position.company.url %>"><% position.company.name %></a>
  <% if position.salary? %>
    <span><% position.salary %></span>
  <% end %>
<% end.to_sentence %>


The to_sentence methods works on Arrays. The reason that it works on your first example...

<%= @blah.collect {|b| b.name}.to_sentence %>

... is because the collect method returns an Array. The each method in your second example will also work because each also returns an Array. So, this will work:

<% blah.each do |b| %>
  ...
<% end.to_sentence %>
0

精彩评论

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