如何在 RUBY 中使我的代码与 ARGV 交互
How to make my code interactive with ARGV in RUBY
这是我的 PigLatin 代码,它运行良好,但我需要让它与 ARGV 交互,它应该是:
$ ruby pig_latin.rb
猪香蕉垃圾苹果大象
=> igpay ananabay 烟灰缸 appleway elephantway
def pig_latin(input)
first_char = input[0,1]
vowels = "aeiouAEIOU"
if vowels.include?(first_char)
word = input[1..-1] + first_char + "way"
else
word = input[1..-1] + first_char + "ay"
end
end
在程序末尾添加:
if __FILE__ == [=10=] # if file is being run as script from command line
puts(ARGV.map { |string| pig_latin(string) }.join(" "))
end
ARGV
是一个字符串数组。您可以使用 map
来应用 pig_latin
更改,然后将它们打印在同一行,由 " "
加入
使用 if __FILE__ == [=15=]
的好处是它不需要您的程序使用 ARGV。例如。你仍然可以将它与 require
.
一起使用
这是一个更 Ruby 的清理版本:
def pig_latin(input)
case (first_char = input[0,1])
when /aeiou/i
# Uses a simple regular expression to detect vowels
input[1..-1] + first_char + "way"
else
input[1..-1] + first_char + "ay"
end
end
# Transform the input arguments into their Pig Latin equivalents
# and combine into a single string by joining with spaces.
piglatined = ARGV.map do |arg|
pig_latin(arg)
end.join(' ')
puts piglatined
这是我的 PigLatin 代码,它运行良好,但我需要让它与 ARGV 交互,它应该是:
$ ruby pig_latin.rb
猪香蕉垃圾苹果大象
=> igpay ananabay 烟灰缸 appleway elephantway
def pig_latin(input) first_char = input[0,1] vowels = "aeiouAEIOU" if vowels.include?(first_char) word = input[1..-1] + first_char + "way" else word = input[1..-1] + first_char + "ay" end end
在程序末尾添加:
if __FILE__ == [=10=] # if file is being run as script from command line
puts(ARGV.map { |string| pig_latin(string) }.join(" "))
end
ARGV
是一个字符串数组。您可以使用 map
来应用 pig_latin
更改,然后将它们打印在同一行,由 " "
使用 if __FILE__ == [=15=]
的好处是它不需要您的程序使用 ARGV。例如。你仍然可以将它与 require
.
这是一个更 Ruby 的清理版本:
def pig_latin(input)
case (first_char = input[0,1])
when /aeiou/i
# Uses a simple regular expression to detect vowels
input[1..-1] + first_char + "way"
else
input[1..-1] + first_char + "ay"
end
end
# Transform the input arguments into their Pig Latin equivalents
# and combine into a single string by joining with spaces.
piglatined = ARGV.map do |arg|
pig_latin(arg)
end.join(' ')
puts piglatined