Assigning values to variables within other statements - Ruby
Archive - Originally posted on "The Horse's Mouth" - 2011-09-07 07:43:44 - Graham EllisIn Ruby, and in Perl too, you can use assignments within other statements and in so doing perform two distinct actions in one line of code. Here's what I mean (using irb - interactive Ruby):
>> j = 16
=> 16
>> print "The value is #{k=j} at the moment"
The value is 16 at the moment=> nil
>> print k
16=> nil
>> ... you'll notice that I've both printed out a line of text including the value of the variable j, and copied it to the variable k, in a single statement.
Operations such as this can also effect the incoming variables, and where they do you need to take care to ensure that you know whether the second use of the variable's value wil be made before or after it is changed. Look at this statement:
print "#{now+=1}"... and ask yourself whether it will be the old value of now, or the new one, that's printed out, And again - in
bob = now += 4will bob be assigned to a copy of the incoming value of now, or the outgoing value once 4 has been added?
In general, the answer to the question "what happens first" comes down tho the languages's precedence tree and any bracketting you have in there (there are some catches with how opertors like += and Perl's ++ interact with brackets). And in general, I'm going to advise that you should usually write the code as two lines if you want to perform two actions.. By separating the operations, you may be making the code a little longer, but you're also making it unambiguous to the inexperienced reader who may come along to maintain the code later. And you're also going to save yourself any problems if you're required to remove one but not both of the operations performed at a later date.
Scenario ... the boss comes along. "Great program, Graham, but a bit verbose on its output. Can you remove the step logging as it run?" So I delete the print statment that I've shown above .. and then the whole program fails as I've also removed the secondary effect of increasing now. Oops!
Full source code example including the statements above - [here]. There's also sample output so you can see how it ran, and what the order was.