Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the feature in Ruby that allows "p *1..10" to print out the numbers 1-10?

Tags:

syntax

ruby

splat

require 'pp'

p *1..10

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

like image 925
Paul H. Avatar asked Apr 02 '09 05:04

Paul H.


2 Answers

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]
like image 195
sris Avatar answered Nov 16 '22 10:11

sris


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.

like image 45
Jon Skeet Avatar answered Nov 16 '22 11:11

Jon Skeet