2

I'm working on implementing Project Euler solutions as semantic Ruby one-liners. It would be extremely useful if I could coerce Ruby to automatically puts the value of the last expression. Is there a way to do this? For example:

#!/usr/bin/env ruby -Ilib -rrubygems -reuler

1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum)

I realize I can simply puts the line, but for other reasons (I plan to eval the file in tests, to compare against the expected output) I would like to avoid an explicit puts. Also, it allots me an extra four characters for the solution. :)

Is there anything I can do?

2
  • Where would you put the puts in this case?
    – tadman
    Jul 14, 2011 at 16:10
  • I want it to be implicit on the last expression of the file. I'm not certain it's possible, but if it is, I figured someone here would know. Jul 14, 2011 at 16:32

4 Answers 4

2

You might try running it under irb instead of directly under a Ruby interpreter.

It seems like the options -f --noprompt --noverbose might be suitable (.

#!/usr/bin/env irb -f --noprompt --noverbose -Ilib -rrubygems -reuler

'put your one-liner here'

The options have these meanings:

  • -f: do not use .irbrc (or IRBRC)
  • --noverbose: do not display the source lines
  • --noprompt: do not prefix the output (e.g. with =>)
1
  • Aha! This does the trick, with only the (almost inconsequential) downside of printing an extra newline. Jul 14, 2011 at 19:01
0
result = calculate_result

puts result if File.exist?(__FILE__)
0

result of eval is last executed operation just like any other code block in ruby

is doing

puts eval(file_contents)

an option for you?

EDIT

you can make use of eval's second parameter which is variables binding

try the following:

do_not_puts = true
eval(file_contents, binding)

and in the file:

....
result = final_result
if defined?(do_not_puts)
  result
else
  puts(result)
end
1
  • I may have been unclear. I want the contents of the file to be implicitly put's when run (similar to the -p flag) at the shell, but there should be no output if the file is eval'd Jul 14, 2011 at 16:34
0

Is it an option to change the way you run scripts?

script.rb:

$_= 1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum) 

invoke with echo nil.txt | /usr/bin/env/ruby -Ilib -rrubygems -reuler -p script.rb, where nil.txt is a file with a single newline.

Your Answer

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

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