ruby - Why the value of the assignment is always the value of the parameter? -


this question has answer here:

would care explain why in older versions of ruby, result of assignment value returned attribute-setting method, after ruby 1.8, value of assignment value of parameter; return value of method discarded. in code follows, older versions of ruby set result 99. result set 2.

class test   def val=(val)     @val = val     return 99   end end  t = test.new result = (t.val = 2) result # => 2 

what reasoning behind change?

it's not uncommon chain assignments when want assign same value multiple variables. more common in other languages.

@user_id = user.id = next_user_id 

but happens when aren't thinking that, , return value isn't same input value?

class user   def id=(name)     @id = name     @modified = true   end    def modified?     @modified   end end 

this code work totally fine until 1 day when go drop in assignment chain above, when of sudden you'll unexpected results.

so, interpreter sort of voodoo , ensures rhs of assignment return value, discarding actual return value.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -