2017-07-13 20 views
0

這是我的PigLatin代碼和它的作品很好,但我需要使它的互動與ARGV,它應該是:如何使我的代碼互動與ARGV在RUBY

$ 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 

回答

1

這裏有一個清理版本更紅寶石般:

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 
+0

感謝@tadman :) –

3

添加這在程序的結尾:

if __FILE__ == $0 # 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__ == $0的好處是,它不需要你的程序中使用ARGV加入。例如。你仍然可以使用它require

+0

感謝@maxpleaner –