这个结果背后的逻辑是什么? [英] What is the logic behind this result?

查看:55
本文介绍了这个结果背后的逻辑是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def foo(_, _='override')
  _
end

p foo("bye bye")
p foo("hello", "world")

输出:

"override"
"hello"

如果结果是:

"override"
"world"

甚至:

"bye bye"
"hello"

但是我得到的结果让我很困惑.

But the result I'm getting causes me confusion.

推荐答案

如果为它传递参数,则默认参数比常规参数更早地计算,否则最后计算.几乎可以肯定,但不确定如何证明.

Default arguments are evaluated earlier in time than regular arguments if an argument is passed for it, otherwise they are evaluated last. Almost certain but unsure how to prove it.

本例中的含义:

在时间 0 调用 p foo("hello", "world")

在时间 1 _ = 'override'

在时间 2 _ = "world"

在时间 3 _ = "hello"

在打印 4 个变量时,您会看到你好"

at time 4 variables are printed and you see "hello"

编辑这里有一些证据:

def foo(_, _='override',_)
  _
end

p foo("bye bye","goodbye")
p foo("hello", "world", "three")

印刷品

"override"
"three"

这篇关于这个结果背后的逻辑是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆