David A. Black wrote:
my_array.delete_if {|a| [*a].include?(“x”) }
=> [5, 3, 4, [“abc”, 3, 5]]
The splat here really isn’t necessary.
The * unpacks an array. It is often used with argument to methods:
def foo(a, b, c)
puts “a:#{a} b:#{b} c:#{c}”
end
my_array = [1,2,3]
foo(*my_array) #=> “a:1 b:2 c:3”
So the splat lets you pass an array as individual arguments. Or it can
work the other way around.
def foo(*args)
puts “arguments: #{args.size}”
end
foo(1,2,3) #=> 3
This example allows individual arguments to be passed in as an array.
This pattern is used a lot throughout rails.
In David’s example:
my_array.delete_if {|a| [*a].include?(“x”) }
The “a” in that code will be each subarray of this main array. *a will
unpack that array into individual elements. And the [] wrapped around
*a will make a new array containing those elements.
This all means that:
a = [1,2,3]
a == [*a] #=> true
So, the simpler way to do this is just:
my_array.delete_if {|a| a.include?(“x”) }
Hopefully that explains the splat a bit.