require 'pp'
p *1..10
This prints out 1-10. Why is this so concise? And what else can you do with it?
require 'pp'
p *1..10
This prints out 1-10. Why is this so concise? And what else can you do with it?
Well:
require pp
imports the pretty-printing functionalityp
is a pretty-printing method with varargs, which pretty-prints each argument*
means "expand the argument into varargs" instead of treating it as a single argumentDoes that explain it adequately? If not, please elaborate on which bit is confusing.
It is "the splat" operator. It can be used to explode arrays and ranges and collect values during assignment.
Here the values in an assignment are collected:
a, *b = 1,2,3,4
=> a = 1
b = [2,3,4]
In this example the values in the inner array (the [3,4]
one) is exploded and collected to the containing array:
a = [1,2, *[3,4]]
=> a = [1,2,3,4]
You can define functions that collect arguments into an array:
def foo(*args)
p args
end
foo(1,2,"three",4)
=> [1,2,"three",4]