Search code examples
rubycommand-lineterminalargumentsargv

Ruby assign more than one arguments from terminal


I'm using the terminal and assigning multiple variables on a ruby file hello_world.rb in the following way:

$ ruby hello_world.rb arg1 arg2 arg3 arg4

If I put

$ ruby hello_world.rb hello world mars jupiter

I need it to display

hello world
hello mars 
hello jupiter

And if I put

$ ruby hello_World.rb whaddup boy girl

it needs to display

whaddup boy
whaddup girl

1st argument will be the first string, and the rest of the arguments will each be listed as 2nd string.

I was able to create the code:

def hello_world(first, *second)
    second.each do |arg|
        puts "#{first} #{arg}"
    end
end

But when I run $ ruby hello_world.rb hello world mars from terminal, it would not display anything. I think I have to use ARGV. I know how to do with only one argument,

def hello_world
    ARGV.each do |arg|
        puts "Hello #{arg}"
    end
end

hello_world

Terminal:

$ ruby hello_world.rb world mars jupiter
#=> Hello world
#=> Hello mars
#=> Hello jupiter

I have no idea how to do it in case of two arguments or more. Any help will be much appreciated. Thank you!


Solution

  • The ARGV constant is just an array, so you can do the following, for example:

    def hello_world
      first = ARGV.shift
      puts ARGV.map { |arg| "#{first} #{arg}" }
    end
    
    hello_world
    

    The method Array#shift will remove and return the first element of an array. In this case the first argument passed from the command line.

    Output:

    $ ruby hello_world.rb hello world mars
    #=> hello world
    #=> hello mars