Why ruby ​​c = method does not allow more than one argument at the end

This is in a shared library, I have to do this backward compatibility.

Original method

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

Need to improve 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 is assigned to currency_code

+4
source share
3 answers

If you want it to be compatible with feedback, use the array features:

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
+5
source

Because it means that it is just an assignment operation. If this operation needs to be parameterized, it makes sense to make it look like a method call. In addition, the presence of multi-parameter assignment operators complicates the grammar of the language.

+3
source

: -

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

:

def rrp_exc_sales_tax=(num)
  if num.is_a?(Hash)
    print "num=#{num["num"]}"
    print "currency_code=#{num["currency_code"]}"
    price_set(1, num["num"], num["currency_code"])
  else
    print "num=#{num}"
    print "currency_code=#{currency_code}"
    price_set(1, num, currency_code)
  end 
end

, , : -

rrp_exc_sales_tax={"num"=>2, "currency_code" => "USD"}

.

+2

Source: https://habr.com/ru/post/1537940/


All Articles