tags:

views:

189

answers:

2
require 'pp'

p *1..10

This prints out 1-10. Why is this so concise? And what else can you do with it?

+6  A: 

Well:

  • require pp imports the pretty-printing functionality
  • p 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 argument
  • 1..10 is range sequence syntax in Ruby

Does that explain it adequately? If not, please elaborate on which bit is confusing.

Jon Skeet
+1 for a concise and purty answer as the 50K mark looms...
Mike Woodhouse
+10  A: 

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]
sris
Why did this get downvoted? My answer didn't go into detail on any one aspect on the grounds that I didn't know which bit was confusing the OP, but this is great for the splat operator.
Jon Skeet