Ruby asterisk packing and unpacking operations

Ruby may be used an asterisk *and double asterisks **complete some packing, unpacking operation, they are referred to splat operator:

  • An asterisk: an array as the basis for packing and unpacking ( refer to article )
  • Two asterisks: the hash as the basis for packing and unpacking ( refer to article )

Two asterisks splat scene is rare, if necessary, refer to refer to the article listed above.

When the splat operator is followed by an array, the array unpack operation is performed: unpacks element list. This unpack effect when you call the function and pass a reference comparison can be reflected.

def f(a,b,c,d)
  p "1.#{a}"
  p "2.#{b}"
  p "3.#{c}"
  p "4.#{d}"
end

arr=%w(aa bb cc dd)
f(*arr)

# 赋值解包:将数组解包成元素列表再赋值给arr变量
# 这过程中会创建一个新的数组保存解包后但要赋值的各元素
arr=*[1,2,3]

Above *arrwith the rear face, splat operator is an array, it does so unpacking operation, unpacking the array into four elements, and sequentially assigned to the parameters a, b, c, d.

When the operator with a splat followed by one or more elements, then perform an array of packaging: Create a new array to hold these elements. This is more common in the function definition, it can also be occasionally seen at the time of the assignment.

def foo(a,b,*args)
  p a
  p b
  p args   #=> 打包成[3,4,5]赋值给参数args
end

foo(1,2,3,4,5)

The following packing, unpacking more classic example:

a,*x=1,2,3    #=> a=1,x=[2,3]

a, (b, *c), *d = 1, [2, 3, 4], 5, 6
   #=> a=1,b=2,c=[3, 4],d=[5, 6]

Guess you like

Origin www.cnblogs.com/f-ck-need-u/p/10930383.html