0

Given that this part of code works,

if @sprint.nil?
  redirect_to sprints_path
else
  @sprint.define_state
end

I don't understand why this part of code doesn't:

@sprint.nil? ? redirect_to sprints_path : @sprint.define_state

I don't know why in the second example the program goes immediately into the else block. Could someone explain how it is possible?

sawa
  • 165,429
  • 45
  • 277
  • 381
Alexandre
  • 58
  • 1
  • 8
  • 3
    You are missing parentheses `@sprint.nil? ? redirect_to(sprints_path) : @sprint.define_state` since the original is on multiple lines the parentheses can be omitted but the ternary version will require them for the code to be interpreted correctly. – engineersmnky Oct 05 '15 at 17:37
  • Welcome to Stack Overflow. Using headings, such as "Situation:" and "Question:" aren't particularly desirable. While it might seem to help, Stack Overflow aims to be like a cookbook of programming problems and answer, a slightly informal version of a reference book. As such, write a clearly thought-out question in a concise manner and you'll do well. – the Tin Man Oct 05 '15 at 17:39
  • It's not idiomatic, and not recommended, that you use ternary statements like `@sprint.nil? ? redirect_to sprints_path : @sprint.define_state ` for flow control. Returning values is great but `redirect_to sprints_path` looks like a change in flow. I'd recommend sticking with the `if` version. – the Tin Man Oct 05 '15 at 17:41
  • Oh sorry and thanks. I would be more carefull – Alexandre Oct 06 '15 at 08:04

1 Answers1

0

I cannot find an explicit documentation, but presumably, the ternary operator ? : has higher precedence than passing an argument to a method. That makes your example be parsed as:

@sprint.nil? ? (redirect_to sprints_path : @sprint.define_state)

with : appearing in an inappropriate position, missing a ?. (Notice that the error is not caused by ? missing a : because that part lays outside of the offending :, latter of which primarily raises a syntax error, and blocks the syntax error that would be raised by the former.)

sawa
  • 165,429
  • 45
  • 277
  • 381