Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ruby method with = at the end not allow more then one argument

Tags:

ruby

This is in a shared library, I have to make this backward compatible.

Original method

   def rrp_exc_sales_tax=(num)
      price_set(1, num, currency_code)
   end

Need to enhance and add currency_code

   def rrp_exc_sales_tax=(num, currency_code=nil)
      print "num=#{num}"
      print "currency_code=#{currency_code}"
      price_set(1, num, currency_code)
   end


some_class.rrp_exc_sales_tax=2, "USD"

num=[2, "USD"]
currency_code=

No value gets assigned to currency_code

like image 330
aarti Avatar asked Dec 26 '22 10:12

aarti


2 Answers

If you want it to be backwards compatible, leverage on the powers of the array:

def rrp_exc_sales_tax=(arr)
  num, currency_code = arr
  price_set(1, num, currency_code)
end

some_class.rrp_exc_sales_tax=2, "USD"
# => num=2
# => currency_code="USD"

some_class.rrp_exc_sales_tax=2
# => num=2
# => currency_code=nil
like image 93
Uri Agassi Avatar answered Apr 05 '23 22:04

Uri Agassi


Because it's meant to look like a simple assignment operation. If that operation needs to be parameterized, it makes more sense to make it look like a method call instead. Also, having multi-parameter assignment statements complicates the language grammar.

like image 33
mipadi Avatar answered Apr 06 '23 00:04

mipadi