0

I'd like to puts a 1 if a test is true and a puts a 0 if it is not. I'd also like to increment a counter that counts each time a test is successful. I have this right now:

puts test1 ? sum += 1 : 0
puts test2 ? sum += 1 : 0
puts test3 ? sum += 1 : 0
puts test4 ? sum += 1 : 0

Obvoiusly the problem is that if i'm incrementing sum each time, then i'm not print 1 but rather the value of sum.

I tried making a little method that incremented sum and then returned 1 like this:

def inc_sum_ret_1(sum)
  sum += 1
  1
end

and called that in place of "sum += 1". This, of course, only incremented 0 to 1 each time.

Is there a good way to do this? I'm more curious from an intellectual standpoint than making my code particularly tidy.

Ramy
  • 20,541
  • 41
  • 103
  • 153

1 Answers1

4

Well, I think the code you're trying to write is

puts test1 ? (sum += 1; 1) : 0
puts test2 ? (sum += 1; 1) : 0
puts test3 ? (sum += 1; 1) : 0
puts test4 ? (sum += 1; 1) : 0

But of course this is not a great bit of code. It would be far better to just use an if, both in terms of code clarity and eliminating repetition.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • this is great - but why, when i tried using curly braces for a block where you have parens, did ruby choke? – Ramy Mar 22 '13 at 19:41
  • 1
    @Ramy: Because that isn't a block — it's just a group of expressions. Blocks can only syntactically follow a message send, which the `?` there is not. – Chuck Mar 22 '13 at 19:45
  • As Chuck says, "this is not a great bit of code". It's not something you really want to do in real code. Yes, it works, but it's not easy to read or understand, so don't get in the habit of writing code like that. Write clearly and cleanly. Your aging brain will thank you later. – the Tin Man Mar 22 '13 at 20:41