In Ruby, how can you call a method using the default argument or with the specified argument without repeating the code?

Let's say I have a ruby ​​method:

def blah(foo=17)
   ...
end

In the code, I want to call blah with a specific argument "blah (a)" or call blah using my default argument "blah ()" Is there a way to do this without specifying the method name twice? I try to avoid:

if a.nil?
  blah()
else
  blah(a)
end

Because it makes the code more complex than it is. Best I can come up with (not a test):

args=[]
args << a unless a.nil?
a.send :blah, args
+3
source share
6 answers

I just tried a few ways and didn't find it, but if you do so much, I wonder how to use the default setting. Try instead:

def blah(foo=nil)
  foo ||= 17
  puts foo
end

blah()
a = nil
blah(a)
a = 20
blah(a)

:

17
17
20
+6

, , :

blah( *[a].compact )
+3

, , , , - :

blah(a || 17)

, blah, , .

+2

def blah(foo = nil)
    foo ||= 17
end

.

nil -value no-argument, , :

def blah
    foo = block_given? ? yield : 17
end

blah         #=> 17
blah { nil } #=> nil
blah { 71 }  #=> 71
0

. , if . . * , .

blah(*
  if a.nil?
    []
  else
    [a]
  end
)

You do not need to back off so, but it looked like indentation to make it clear.

0
source

I was looking for the same thing. (I think this is almost a mistake in the Ruby specs) I think I will resolve it in a different way using the hash option.

def foo(options={})
  bar = options.delete(:bar) || :default
  puts bar
end

foo 
#=> default

foo :bar => :something
#=> something

a = nil
foo :bar => a
#=> default

It is more extensible and readable for any rubist.

0
source

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


All Articles