Home > Software engineering >  Ruby - permutation program in one line
Ruby - permutation program in one line

Time:03-13

just started ruby :)

I am creating a small ruby program where a user inputs a string of letters and it prints all the possible permutations.

I am trying to write a function that is only 1 line long, but im having trouble getting it to run

Any help please :)

puts "Enter phrase:"
input_string = gets.split("")

#function
print input_string.permutation().to_a

CodePudding user response:

Try calling chomp() before calling split():

puts "Enter phrase:"
input_string = gets.chomp().split("")
print input_string.permutation().to_a, "\n"

Example Usage:

Enter phrase:
ABC
[["A", "B", "C"], ["A", "C", "B"], ["B", "A", "C"], ["B", "C", "A"], ["C", "A", "B"], ["C", "B", "A"]]

Try it out here.

CodePudding user response:

In Ruby, you can always write any program on one line, because line breaks are always optional. They can always be replaced with an expression separator (i.e. semicolon ;), a keyword (e.g. then, do), or sometimes just whitespace (e.g. def foo() 42 end).

In your case, that would look like this:

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?
  • Related