13
\$\begingroup\$

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?

\$\endgroup\$
  • 4
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Oct 23 '17 at 17:52
  • \$\begingroup\$ 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. \$\endgroup\$ – Stan Strum Oct 24 '17 at 18:28
7
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ ARGV can also be accessed as $* which saves two bytes \$\endgroup\$ – Snack Oct 23 '17 at 18:00
  • 4
    \$\begingroup\$ @Snack Hehe, golfing a tips answer :) \$\endgroup\$ – AdmBorkBork Oct 23 '17 at 18:02
6
\$\begingroup\$

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

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.