Ruby 从终端分配多个参数

Ruby assign more than one arguments from terminal

我正在使用终端并按以下方式在 ruby 文件 hello_world.rb 上分配多个变量:

$ ruby hello_world.rb arg1 arg2 arg3 arg4

如果我输入

$ ruby hello_world.rb hello world mars jupiter

我需要它来显示

hello world
hello mars 
hello jupiter

如果我把

$ ruby hello_World.rb whaddup boy girl

需要显示

whaddup boy
whaddup girl

第一个参数将是第一个字符串,其余参数将分别列为第二个字符串。

我能够创建代码:

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

但是当我从终端运行 $ ruby hello_world.rb hello world mars时,它不会显示任何东西。我想我必须使用 ARGV。我知道如何处理只有一个参数,

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

hello_world

航站楼:

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

如果有两个或更多参数,我不知道该怎么做。任何帮助都感激不尽。谢谢!

ARGV常量只是一个数组,所以你可以这样做,例如:

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

hello_world

方法 Array#shift 将删除并 return 数组的第一个元素。在这种情况下,第一个参数从命令行传递。

输出:

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

您需要做的就是使用您的第一个 hello_world 方法,但使用 ARGV 的元素调用它,而不是 ARGV 本身,使用 splat:

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

hello_world *ARGV
# ..........^

记录在 http://ruby-doc.org/core-2.2.3/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion