4

I'm looking at a ruby method

def test(*)
  puts "hello"
end

I'm confused about the *. Obviously if I run test it returns "hello". But what if I pass an argument into test...

test("this argument")

How do I call that method within the test method yet still have the splatter? I'm just awfully confused about having a splatter without a name. How does it work?

thank_you
  • 11,001
  • 19
  • 101
  • 185
  • 2
    This might help: http://stackoverflow.com/questions/5249537/naked-asterisk-as-parameter-in-method-definition-def-f – orde Nov 08 '16 at 20:33
  • @orde Thanks. But what I want to know is how can I call an argument that is passed into the method. Do I have to define it as `def test(*args)` then? – thank_you Nov 08 '16 at 20:37
  • I'll be honest: first time I've seen the naked splat operator. But--if you do something like `def foo(*args); puts args; end`--then the method arguments are collected into an `args` array, and you can do `foo(1,2) #=> 1 2`. – orde Nov 08 '16 at 21:02
  • 1
    Basically, when you see a splat without a name, it means "I don't care about parameters here". If you do care, name the parameters. – Sergio Tulentsev Nov 08 '16 at 21:04

1 Answers1

3

This post has a fairly detailed low level explanation: http://blog.honeybadger.io/ruby-splat-array-manipulation-destructuring/

To quote the most relevant part:

def go(x, *args, y)
  puts x # => 1
  puts y # => 5
  puts args.inspect # => [2,3,4]
end

go(1, 2, 3, 4, 5)
whodini9
  • 1,434
  • 13
  • 18
  • 2
    Please add a summary pf the blog post to your answer. At least describe the parts answering the question here. Link-only answers are frowned upon on Stack Overflow since external links tend to deteriorate and vanish quickly. – Holger Just Nov 08 '16 at 21:04
  • Fixed and in production – whodini9 Nov 08 '16 at 21:25
  • So this part makes sense to me. What I'm confused about is what happens if the args isn't there? Am I forced to put the args into the method parameters in order to get the parameters I want? I assume so. – thank_you Nov 08 '16 at 21:33
  • The params in ruby are by default taken in order. – whodini9 Nov 08 '16 at 21:43
  • Sorry I didn't finish that comment, but there are two solutions. 1. initialize values def go(x = nil, ...) or – whodini9 Nov 08 '16 at 21:44
  • What is the or? – thank_you Nov 08 '16 at 22:19