Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

**args as function parameter in Ruby

I understand that **args is interpreted as a hash containing all key value pairs passed to a function but I don't understand why that would be preferred over a typical parameter. For example, I have the following two functions.

def test(some_string, hash)
    puts hash
    puts hash.class # => Hash
end


def test_two(some_string, **hash)
    puts hash
    puts hash.class # => Hash
end 

calling test("test string", a: 1, b: 2) or test_two("test string", a: 1, b: 2) produces the exact same result. What is the benefit of using ** as a parameter value?

question from:https://stackoverflow.com/questions/65852906/args-as-function-parameter-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ruby 2.7 started more clearly differentiating between keyword arguments and regular hashes. **args is for keyword arguments. Some implications:

def test3(some_string, foo:, **args)
  puts args
end

test3('a', foo: 'b', bar: 'c') # => {:bar=>"c"}

works as expected, however

def test3(some_string, foo:, hash)
  puts args
end # => syntax error

def test3(some_string, hash, foo:)
  puts args
end # works so far

test3('a', foo: 'b', bar: 'c')
# warning: Passing the keyword argument as the last hash parameter is deprecated
# ArgumentError (missing keyword: :foo)

Once you upgrade to ruby 3, the warnings turn to errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...