有没有办法在Ruby中使用&符号和冒号运算符使用多个属性/方法?

时间:2018-10-16 19:43:25

标签: ruby

是这样的:给定一个foo对象数组,它们的属性为bar,该属性还具有一个名为baz的属性:

foos.each(&:bar.baz)

我可以很容易地用bar来获得所有foos.each(&:bar),但是我不能拥有baz属性(或者可能有很多其他属性),因为它给了我错误: TypeError: wrong argument type String (expected Proc)

4 个答案:

答案 0 :(得分:5)

使用.map

foos.map(&:bar).each(&:baz)

这会将您的foo项数组变成bar项数组,让您可以在其上调用.each

答案 1 :(得分:3)

Array#each返回其接收者,因此它可能不是您所寻找内容的最佳示例。假设我们有

https://login.microsoftonline.com/te/your-tenant-name.onmicrosoft.com/oauth2/authresp

想要

arr = [['a', 'b'], ['c', 'd']]

要使用一个和号,可以写一个

arr.map(&:first).map(&:upcase)
  #=> ["A", "C"]

arr.map(&Proc.new { |e| e.first.upcase }) #=> ["A", "C"] 将proc转换为块,导致

&

要执行。

答案 2 :(得分:2)

  

&符冒号运算符是否可能

不。主要是因为没有“和号冒号”这样的东西。这个

<activity
    android:name=".DetailActivity"
    android:theme="@style/DetailTheme"/>

是编写此内容的一种较短方法

foos.each(&:bar)

另请参阅其他答案。

答案 3 :(得分:1)

最好的选择是只使用常规的块语法:

&:sym

例如,由于方法名称是动态的,如果您仍想使用foos.each(&Xf.pipe(:bar, :baz)) 类型的语法,则可以签出Xf gem。它使您能够:

def pipe(*fns)
  Proc.new do |target|
    new_value = target
    fns.each { |fn| new_value = fn.to_proc.call(new_value) }
    new_value
  end
end

require 'ostruct'
# openstruct used to emulate objects that would respond to .foo.bar
foos = []
foos << OpenStruct.new(foo: OpenStruct.new(bar: 'hello'))
foos << OpenStruct.new(foo: OpenStruct.new(bar: 'world'))
foos.each(&pipe(:foo, :bar))

您可以简单地通过使用pipe方法来复制功能而无需包含gem:

global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
相关问题