Ruby - 一行排列程序
Ruby - permutation program in one line
刚开始ruby:)
我正在创建一个小的 ruby 程序,用户输入 一串字母 并打印所有可能的排列。
我正在尝试编写一个只有 1 行长的 函数 ,但我无法将它写到 运行
任何帮助请:)
puts "Enter phrase:"
input_string = gets.split("")
#function
print input_string.permutation().to_a
尝试调用 chomp()
before calling split()
:
puts "Enter phrase:"
input_string = gets.chomp().split("")
print input_string.permutation().to_a, "\n"
用法示例:
Enter phrase:
ABC
[["A", "B", "C"], ["A", "C", "B"], ["B", "A", "C"], ["B", "C", "A"], ["C", "A", "B"], ["C", "B", "A"]]
试试看here.
在Ruby中,您可以始终将任何程序写在一行上,因为换行符始终是可选的。它们始终可以替换为表达式分隔符(即分号 ;
)、关键字(例如 then
、do
),或者有时只是空格(例如 def foo() 42 end
)。
在你的情况下,它看起来像这样:
puts "Enter phrase:"; input_string = gets.split(""); print input_string.permutation().to_a
However, focusing on the number of lines is generally not a good idea as it does not necessarily increase readability. We use multiple lines in text to improve readability, so why should the same not also be true for code? Or do you think that writing this paragraph on one line has improved anything?
刚开始ruby:)
我正在创建一个小的 ruby 程序,用户输入 一串字母 并打印所有可能的排列。
我正在尝试编写一个只有 1 行长的 函数 ,但我无法将它写到 运行
任何帮助请:)
puts "Enter phrase:"
input_string = gets.split("")
#function
print input_string.permutation().to_a
尝试调用 chomp()
before calling split()
:
puts "Enter phrase:"
input_string = gets.chomp().split("")
print input_string.permutation().to_a, "\n"
用法示例:
Enter phrase:
ABC
[["A", "B", "C"], ["A", "C", "B"], ["B", "A", "C"], ["B", "C", "A"], ["C", "A", "B"], ["C", "B", "A"]]
试试看here.
在Ruby中,您可以始终将任何程序写在一行上,因为换行符始终是可选的。它们始终可以替换为表达式分隔符(即分号 ;
)、关键字(例如 then
、do
),或者有时只是空格(例如 def foo() 42 end
)。
在你的情况下,它看起来像这样:
puts "Enter phrase:"; input_string = gets.split(""); print input_string.permutation().to_a
However, focusing on the number of lines is generally not a good idea as it does not necessarily increase readability. We use multiple lines in text to improve readability, so why should the same not also be true for code? Or do you think that writing this paragraph on one line has improved anything?