Advice for ruby

13

1

How can I shorten:

p=gets.to_i
a=gets
b=gets.to_i

If my input is an integer, followed by a string, followed by an integer?

Zawada

Posted 2017-10-23T17:31:48.037

Reputation: 131

4Welcome to PPCG! – Martin Ender – 2017-10-23T17:52:34.810

For the people that will say that this is off topic, if you want to argue it is, read through meta and then message me. – Stan Strum – 2017-10-24T18:28:24.090

Answers

7

Use ARGV ($*) and mass assignment

(disclaimer: I don't know Ruby, but this works on TIO)

p,a,b=$*
p=p.to_i
b=b.to_i

28 26 bytes instead of 30 (thanks to Snack for pointing out the $* trick)

AdmBorkBork

Posted 2017-10-23T17:31:48.037

Reputation: 41 581

ARGV can also be accessed as $* which saves two bytes – Snack – 2017-10-23T18:00:28.147

4@Snack Hehe, golfing a tips answer :) – AdmBorkBork – 2017-10-23T18:02:23.117

6

Use a lambda

Answers are typically allowed as lambda functions with your input/output being the parameters/return value of the lambda, so you can do this:

->p,a,b{...}

If you assigned this to a variable f then it would be called as

f[p,a,b]

It's generally fine to assume the types of the inputs as well, but to be safe you can mention it in your answer.

Relevant meta post about acceptable input/output methods

Snack

Posted 2017-10-23T17:31:48.037

Reputation: 251

6

If you need a full program with stdin/stdout io for some reason, the shortest you can do is use the -n flag to shorten one call to gets.to_i to eval$_:

p=eval$_
a=gets
b=gets.to_i

The -n flag surrounds your code with while gets ... end, so the program will loop if more input is supplied than your program consumes.

Pavel

Posted 2017-10-23T17:31:48.037

Reputation: 8 585