English 中文(简体)
我怎样才能得到一个街区中元素的数量?
原标题:How do I get the number of elements in a block?
  • 时间:2012-05-24 17:36:03
  •  标签:
  • ruby

我有两个文件init.rb airport.rb

我如何计算与价值相符的物品数量?

init.rb:

airport1.airplanes_count { |a| a.aircraft_type == "Boeing 747" }

机场.rb:

def airplanes_count
  @airplanes.each  { |a|  a if yield(a)  }
end

如果 airmount_type = Boeing 747,我需要得到一些飞机:

=> 2 

代替飞机名称

=> #<Airplane:0x0000000155e348>
   #<Airplane:0x0000000155e028>"
最佳回答

您的方法应该像这个样子 :

def airplanes_count
    @airplanes.count{ |a|  a if yield(a)  }
end
问题回答

Ruby 已经在所有计数器( 如Hashes, Array,...) 中带来了 < a href=" http:// ruby- doc. org/core-1.9.3/Enumberable.html#method- i- count" rel= "nofollow"\\ code>count 的方法。 您可以像这样“ 向前移动” 您的区块 :

def airplanes_count(&block)
  @airplanes.count(&block)
end

这样做有更好的方法... 但是... 如果你不想改变太多的代码... 你可以把飞机的体形 改成这条线

def airplanes_count
    @airplanes.inject(0)  { |count,a|  yield(a)?  (count + 1) : count  }
end

这会让你得到你要找的东西





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签