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

2

5
require 'pp'

p *1..10

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

Carbonization answered 2/4, 2009 at 5:23 Comment(0)
O
13

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]
Oneida answered 2/4, 2009 at 5:38 Comment(1)
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.Rectocele
R
8

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.

Rectocele answered 2/4, 2009 at 5:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.