1

I'm looking for the shortest ruby equivalent of this Python snippet

a, b, c, d = map(int, raw_input().split(" ")) 

is there anything shorter than this?

a, b, c, d = gets.split(" ").map &:to_i

2 Answers 2

2

Without argument, String#split split the string on whitespaces ($;):

"1 2 3 4\n".split
# => ["1", "2", "3", "4"]

In other word, you don't need to call chomp to remove trailing newline:

a, b, c, d = gets.split.map &:to_i

str.split of Python is similar (no need to specify argument):

>>> "1 2 3 4\n".split()
['1', '2', '3', '4']
Sign up to request clarification or add additional context in comments.

Comments

1

The default value for the split pattern is $;, and the default value for $; is nil. A pattern of nil means "split on whitespace", which is not 100% equivalent to what you have (which is "split on a single space character"), but if you can live with that, then you can shorten your expression to:

a, b, c, d = gets.split.map &:to_i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.