Setting default values ​​for a method

Given the method:

def foo(a,b=5,c=1)
    return a+(b*c)
end

Startup foo(1)should return 6. But how are you going to do something like this: foo(1,DEFAULT,2). I need to change the third value, but use the second default value.

How do you do this? (Note: I cannot just change the order of the variables, because they are the arguments for the gem method)

+4
source share
2 answers

You cannot do this in terms. This situation is exactly why the name parameters (keyword) were introduced in Ruby 2. But your parameters with default values ​​are not called according to the terms of the question.

, - - , , ( a ), , .

, a a b, a b c. a c , , .

spring .

  • , . , , , :

    foo(1,5,2)
    
  • , , :

    def foo(a,b=5,c=1)
      return a+(b*c)
    end
    def bar(a,b:5,c:1)
      return foo(a,b,c)
    end
    bar(1,c:2) # => 11
    
+7

- nil, :

def foo(a,b=nil,c=nil)
  b ||= 5
  c ||= 1

  a + (b * c)
end

:

def foo(a,b=nil,c=nil)
  a + (b || 5) * (c || 1)
end
+1

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


All Articles