方法调用中的double-splat做什么?

时间:2018-08-18 03:06:33

标签: ruby double-splat

在准备Ruby Association Certified Ruby Programmer Exam的同时,我正在解决prep test并遇到以下情况:

def add(x:, y:, **params)
  z = x + y

  params[:round] ? z.round : z
end


p add(x: 3, y: 4) #=> 7 // no surprise here
p add(x: 3.75, y: 3, round: true) #=> 7 // makes total sense
options = {:round => true}; p add(x: 3.75, y: 3, **options) #=> 7 // huh?

现在,我知道如何将双引号用于将参数中的参数转换为哈希,例如:

def splat_me(a, *b, **c)
  puts "a = #{a.inspect}"
  puts "b = #{b.inspect}"
  puts "c = #{c.inspect}"
end

splat_me(1, 2, 3, 4, a: 'hello', b: 'world')

#=> a = 1
#=> b = [2, 3, 4]
#=> c = {:a=>"hello", :b=>"world"}

但是,我也知道您不能随机地双连击。

options = {:round => true}
**options

#=> SyntaxError: (irb):44: syntax error, unexpected **arg
#=> **options
#=>   ^

问题

方法调用(不是定义)中的双短划线(**)有什么用途?

简单地说,这是什么时候:

options = {:round => true}; p add(x: 3.75, y: 3, **options)

比这更好:

options = {:round => true}; p add(x: 3.75, y: 3, options)

编辑:测试双splat的有效性(未找到)

有或没有Args都是一样的。

def splat_it(**params)
  params
end

opts = {
  one: 1,
  two: 2,
  three: 3
}

a = splat_it(opts)   #=> {:one=>1, :two=>2, :three=>3}
b = splat_it(**opts) #=> {:one=>1, :two=>2, :three=>3}

a.eql? b # => true

我的意思是,您甚至可以毫无问题地将哈希传递给使用关键字params定义的方法,并且它将智能地分配适当的关键字:

def splat_it(one:, two:, three:)
  puts "one   = #{one}"
  puts "two   = #{two}"
  puts "three = #{three}"
end

opts = {
  one: 1,
  two: 2,
  three: 3
}

a = splat_it(opts)   #=> {:one=>1, :two=>2, :three=>3}
#=> one   = 1
#=> two   = 2
#=> three = 3

b = splat_it(**opts) #=> {:one=>1, :two=>2, :three=>3}
#=> one   = 1
#=> two   = 2
#=> three = 3

使用适当的to_hto_hash方法在随机类上执行双splat不能做没有它就做不到的事情:

Person = Struct.new(:name, :age)

Person.class_eval do
  def to_h
    {name: name, age: age}
  end

  alias_method :to_hash, :to_h
end

bob = Person.new('Bob', 15)

p bob.to_h #=> {:name=>"Bob", :age=>15}


def splat_it(**params)
  params
end

splat_it(**bob) # => {:name=>"Bob", :age=>15}
splat_it(bob)   # => {:name=>"Bob", :age=>15}

1 个答案:

答案 0 :(得分:3)

可能需要解构输入参数。在这种情况下,简单的哈希将不起作用:

params = {foo: 42, bar: :baz}
def t1(foo:, **params); puts params.inspect; end
#⇒ :t1
def t2(foo:, params); puts params.inspect; end 
#⇒ SyntaxError: unexpected tIDENTIFIER
def t2(params, foo:); puts params.inspect; end
#⇒ :t2

现在让我们对其进行测试:

t1 params
#⇒ {:bar=>:baz}
t2 params
#⇒ ArgumentError: missing keyword: foo
t2 **params
#⇒ ArgumentError: missing keyword: foo

也就是说,双splat允许透明的参数解构。

如果好奇为什么会有用,在上面的示例中,foo在此语法内的方法调用中被设置为强制参数。


对函数的调用中的未修饰参数允许作为一种健全性检查,以确保所有键都是符号:

h1 = {foo: 42}
h2 = {'foo' => 42}
def m(p); puts p.inspect; end
m **h1
#⇒ {:foo=>42}
m **h2
#⇒ TypeError: wrong argument type String (expected Symbol)
相关问题