分享两篇文章,介绍 Splat operator 和 Ruby2.0 引入的 Double Splat operator.
Splat goes Ruby Drat! - Ruby has a Double Splat
ahoy :a, 345, hello: :world # => [:a, 345, {:hello=>:world}]
- 将Array参数转化为list
```ruby
def ahoy(from, to)
puts "#{to.capitalize}, #{from.capitalize} says ahoy!"
end
even_stephens = %w(steven stephen)
ahoy even_stephens # Array is interpreted as the first argument, and to_matey won’t be set. An ArgumentError is raised.
ahoy *even_stephens # Array is reversed to a list and all the arguments are filled out.
# => Stephen, Steven says ahoy!
hello('denny', :a, :b, upcase: true) { 'block this!' }
```ruby
# Works fine:
def hello(name = nil, *args)
# Throws SyntaxError:
def hello(*args, name = nil)
# Using several splats in a definition SyntaxErrors too:
def hello(a, *args, b, *brgs)
ActiveSupport::Notifications.subscribe('render') do |*, payload| puts payload end
ActiveSupport::Notifications.subscribe('render') do |*args| payload = args.last puts payload end
- 赋值时的使用
```ruby
a, b = [:a, :b]
a # => :a
b # => :b
a, b = [:a, :b, :c] # :c is lost
a # => :a
b # => :b
a, *rest = [:a, :b, :c]
a # => :a
rest # => [:b, :c]
a, *= [:a, :b, :c]
a # => :a
a ,= [:a, :b, :c]
a # => :a
class SupremeSnapper < WhipperSnapper def initialize(*) super @agility = 100_000 end end
### Double Splat的用法
- Obligatorily Optional(如何翻译?)
```ruby
def hello(**options)
p options
end
hello
# options: {}
hello name: 'Kasper'
# options: { :name => 'Kasper' }
类似于 optional arguments
def hello(options = {})
end
hello 'Kasper'
hello upcase: true
`**`之前的参数必须是可选的!
```ruby
def hello(name, **options)
p name
p options
end
hello upcase: true
# name: { :upcase => true }
# options: {}
hello # raises "ArgumentError: missing keyword: name" as expected
hello name: 'Kasper', play_style: :laces_out
```ruby
def hello(name:, **options)
p name
p options
end
hello name: 'Kasper', play_style: :laces_out
# name: 'Kasper'
# options: { :play_style => :laces_out }
hello play_style: :laces_out
# ArgumentError: missing keyword: name
# 加入默认值后
def hello(name: nil, **options)
p name
p options
end
hello play_style: :laces_out
# nil
# {:play_style=>:laces_out}
options = { a: 'b' }
{ c: 'd', **options } # => { :c => "d", :a => "b" }
*
可以展开一个数组,两个用法还是挺接近的。
a=[1,3]
# => [1, 3]
[2, *a]
# => [2, 1, 3]
hello { |options| p options[:name] }
可以简写
```ruby
hello { |name:| p name }
# Outputs "Kasper"
def hello
yield name: 'Kasper', play_style: :laces_out
end
hello { |name:, **| p name }
# Outputs "Kasper"