I'm having trouble finding an authoritative example or discussion of this concept. If I have 2 variables in my Ruby method that are numbers, and I need to initialize them to zero. They will be used as counters. Is this OK or safe? It works in my tests.
Instead of this:
foo = 0 bar = 0
You can do this?
foo = bar = 0
It seems like a nice way to save on lines and still be expressive. Or, is this a bad practice? I realize I would be sacrificing readability a little. But, in a small Ruby method (<10 lines), that might not be a valid concern.
You can declare multiple variables in a single line. However, there are more efficient ways to define numerous variables in JavaScript. First, define the variables' names and values separated by commas using just one variable keyword from var , let or const.
When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.
int a, b, c; You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .
Declaring each variable on a separate line is the preferred method. However, multiple variables on one line are acceptable when they are trivial temporary variables such as array indices.
This works, but you should know that it's only safe for your situation because you're using the variables for numbers, which are immutable in Ruby. If you tried the same thing with a string, for example, you could end up with some behavior you didn't expect:
ruby-1.9.2-p180 :001 > foo = bar = "string" => "string" ruby-1.9.2-p180 :002 > foo.upcase! => "STRING" ruby-1.9.2-p180 :003 > bar => "STRING"
It is fine practice to initialize two variables on the same line as long as the value being assigned as short and easy to follow. You can even assign two different values using the array syntax.
foo = bar = 123 foo #=> 123 bar #=> 123 foo, bar = 1, 2 foo #=> 1 bar #=> 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With