3 ms·
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 fa
by kbenson 11y ago
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).
- matthewmacleod 11y agoAh, 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
- kbenson 11y agoAnd 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.