Geo*_*off 6 ruby ruby-on-rails
有没有简单的说法:否则,如果没有任何循环,请显示"没有对象".似乎应该有一个很好的语法方法来做这个而不是计算@ user.find_object("param")的长度
你可以这样做:
if @collection.blank?
# @collection was empty
else
@collection.each do |object|
# Your iteration logic
end
end
Run Code Online (Sandbox Code Playgroud)
Rails视图
# index.html.erb
<h1>Products</h1>
<%= render(@products) || content_tag(:p, 'There are no products available.') %>
# Equivalent to `render :partial => "product", @collection => @products
Run Code Online (Sandbox Code Playgroud)
render(@products)
nil
当@products
空的时候会返回.
红宝石
puts "no objects" if @collection.blank?
@collection.each do |item|
# do something
end
# You *could* wrap this up in a method if you *really* wanted to:
def each_else(list, message)
puts message if list.empty?
list.each { |i| yield i }
end
a = [1, 2, 3]
each_else(a, "no objects") do |item|
puts item
end
1
2
3
=> [1, 2, 3]
each_else([], "no objects") do |item|
puts item
end
no objects
=> []
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3715 次 |
最近记录: |