Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This comes directly from Ruby via Coffeescript.

It's aligned with a general approach of reducing syntax noise, and it can result in some really nice, clean code. It leads to a whole class of syntax possibilities, like implicit returns.

There are probably some performance arguments against this in the case of Coffeescript, especially wrt constructing expensive return values that are immediately discarded. The consistency is nice, however.



Does Ruby allow the value of the if statement to be used as the RHS of an assignment? That's surprising. In Perl, which I assume they got that from (it's a fairly safe bet, Ruby is heavily Perl influenced), postconditionals are not allowed to be used as a statement, they are statement modifiers. You can do this:

  $v = 1 if $v < 1;
  return unless defined $param;
  die "died!" unless $param > 10;
But you cannot:

  $v = if $v;
You also cannot use else on postconditionals (if it's that complex, you need a traditional if statement).


Ah, that's interesting – they become expression modifiers instead.

  x = (:false if true)
  => :false
  
  x = (:false if false)
  => nil
Any other if statement does appear to be treated as a value:

  x = if true then 5 else 10 end
  => 5


And that's different than in Perl, where they aren't statement modifiers (I slightly misspoke), they really are just rearranged into single statement if blocks. That is, if the postconditional is false, the statement is not executed at all.

  my $x = 1;
  $x = 10 if $x > 1;
  say $x; # 1
Personally I find the assignment of the if/else statement's return value distasteful, as it's both complex to read and mixes a portion of a natural pattern of thinking while later abandoning it, making it unintuitive. At that level, I prefer a ternary operator.


I think Ruby got it from PERL... And I'm not sure if PERL was the first language to use these, either.

EDIT: of course, there's Smalltalk, where postfix conditionals and loops are the only form available. Maybe Ruby got inspired by those.


Algol 60 had conditional expressions. Pretty much every functional language and LISP has them. They've also been in use in mathematics for longer than computers have been around.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: