Ruby 可枚举 select 具有可选限制/查找

Ruby enumerable select with optional limit / find

我有以下可枚举到 select 个基于类别 (HAML) 的文章

- blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }.each_with_index do | article, index |
= index

我希望能够限制此调用,但可以选择,即 return 2 或者 return all

- blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }.first( 2 ).each_with_index do | article, index |
= index

即随着 first( 2 )

的引入

但是有选择地做像 first( 'all' ) 或 first( ) 这样的事情是不可能的

谢谢

def some_meth(data, option)
  raise 'Invalid option' if !option.is_a?(Integer) || option != 'all'

  option == 'all' ? data : data.first(option)
end

用法:

- some_meth(blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }, 2)

- some_meth(blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }, 'all')