简体   繁体   中英

How to pass kwargs in ruby function? Based on python example

Env:

$ ruby --version
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]

Question:

There is example on python:

def any_func(a, b=2, c = 0, d=None):
    return c

print(any_func(25, c=30))  # will print 30

How can I do the same on ruby?
How "kwargs" is called on ruby? I would like to know it for further searching.

I tried following code on ruby:

#!/usr/bin/env ruby
def any_func(a, b = 2, c = 0, d = nil)
  c
end

puts any_func(25, c = 30)  # will print 0, 30 is expected

In Ruby you need to use hash-like syntax

def any_func(a, b: 2, c: 0, d: nil)
  c
end

any_func(25, c: 30)

def fun(a=1) only sets a default value. And if you have any_func(25, c = 30) , it means "call any_func with two arguments, 25 and result of expression c = 30 (that is 30)"

Read more

Ruby has both positional arguments and keyword arguments. Differing from Python, you can't mix them but have to declare them with their respective syntax and provide them accordingly in method calls.

def any_func(a, b: 2, c: 0, d: nil)
  c
end

puts any_func(25, c: 30)

You can refer to the official syntax documentation to learn more about how to declare and call methods with arguments.

As for your own example of calling your any_func method with any_func(25, c = 30) , what happened here is that you have created the local variable c in the calling context with the value 30 . You have also passed this value to the second (optional) argument b of your method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM