0

Let's say we have this code:

def something(*someargs)
      return *someargs.join(",")
end

Now, I found you can reference *someargs just like any other variable anywhere in the method definition. But I tried this...returning *someargs as a string, separated with a comma. Yet, when I call this method:

a = something(4, 5)
p a.class # => Array
p a #> ["4,5"]

why does something(4,5) still returns an array? If I do something like this:

[4, 5].join(",")

the result will be a string not in an array. So my question would be, how do I make the "something" method return an actual string which contains all the arguments as a string. And it's weird because if I do *someargs.class, the result is "Array", yet it doesn't behave like a typical array...

4

2 回答 2

2

试试下面:

def something(*someargs)
      return someargs.join(",")
end
a = something(4, 5)

p a.class # => String
p a # => "4,5"

一个例子来解释你的情况:

a = *"12,11"
p a # => ["12,11"]

因此,当您这样做时return *someargs.join(",")someargs.join(",")将字符串创建为"4,5"。但是现在您再次在评估的字符串上使用 splat operator(*) 并"4,5"使用赋值操作,例如a = *"4,5"。所以最后你得到了["4,5"]

在此处阅读更多使用 splat 运算符的场景 -Splat Operator in Ruby

希望有帮助。

于 2013-10-30T13:00:38.380 回答
-3
  • 带有 splat*...的对象不是对象。你不能引用这样的东西,也不能将它作为参数传递给方法,因为没有这样的东西。但是,如果您有一个可以采用多个参数的方法,例如puts,那么您可以执行以下操作:

    puts *["foo", "bar"]
    

    在这种情况下,不存在*["foo", "bar"]. splat 运算符将其扩展为多个参数。它相当于:

    puts "foo", "bar"
    
  • 关于为什么someargssomeargs.join(","). 那是因为join不是破坏性的方法。它对接收器没有任何作用。此外,对象不能通过破坏性方法更改其类。someargs将引用从数组更改为字符串的唯一方法是重新分配它。

于 2013-10-30T13:40:31.293 回答