2 Replies - 1865 Views - Last Post: 19 December 2011 - 04:35 PM Rate Topic: -----

#1 Duckington  Icon User is offline

  • D.I.C Addict

Reputation: 170
  • View blog
  • Posts: 608
  • Joined: 12-October 09

Quick Loop Question

Posted 09 December 2011 - 10:58 AM

I saw notation for a loop like this yesterday:

print *(1..10)



And it works, but I can't find any documentation about it ( using the *() ) anywhere. Does anyone have any links to information about it? Or could explain how else you can use that notation/what it's limitations are, etc..?

Thanks.
Is This A Good Question/Topic? 1
  • +

Replies To: Quick Loop Question

#2 The Neoracle  Icon User is offline

  • Check, check, 1, 2.
  • member icon

Reputation: 21
  • View blog
  • Posts: 4,097
  • Joined: 30-March 01

Re: Quick Loop Question

Posted 09 December 2011 - 11:08 AM

1..10 is a Range object.

() isn't anything special

* is an "array splat". * just calls .to_a on something

Do this in rib:

a = 1..10
a.class

print a.to_a

There isn't any looping going on, you are just creating a range from 1 to 10 and then implicitly calling to_a on it which expands the range to a full array.
Was This Post Helpful? 3
  • +
  • -

#3 noahgibbs  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 17
  • Joined: 18-December 11

Re: Quick Loop Question

Posted 19 December 2011 - 04:35 PM

View PostThe Neoracle, on 09 December 2011 - 10:08 AM, said:

1..10 is a Range object.

() isn't anything special

* is an "array splat". * just calls .to_a on something


Actually, the splat is a little bit different than just calling .to_a. Here's an irb excerpt:

ruby-1.9.2-p180 :001 > p [1, 2, 3]
[1, 2, 3]
=> [1, 2, 3]
ruby-1.9.2-p180 :002 > p *[1, 2, 3]
1
2
3
=> [1, 2, 3]
ruby-1.9.2-p180 :003 > p [1, 2, 3].to_a
[1, 2, 3]
=> [1, 2, 3]

See how the the splat does something different than the other two? That's because splat is the same as passing the array as arguments to the method. So the difference is this:

Splat: "print 1, 2, 3"
No splat: "print [1, 2, 3]"

In the splat form, 1, 2, and 3 are three parameters passed to the method. In the no-splat form, print gets a single argument which is the array [1, 2, 3]. It's subtle, but they're different.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1