为什么变量名不能以`?`结尾而方法名可以? [英] Why can't a variable name end with `?` while a method name can?

查看:42
本文介绍了为什么变量名不能以`?`结尾而方法名可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法名称可以以问号结尾 ?

A method name can end with a question mark ?

def has_completed?
  return count > 10
end

但变量名不能.

这是什么原因?变量名也以同样的方式结尾不是很方便吗?鉴于我们通常无法仅通过查看名称 foobar 来判断 foobar 是方法还是变量,那么为什么 会出现异常?代码>案例?

What is the reason for that? Isn't it convenient to have variable names ending the same way too? Given that we usually can't tell whether foobar is a method or a variable just by looking at the name foobar anyway, why the exception for the ? case?

我应该如何处理这个问题?也许总是在代码中使用 hasis ?

And how should I work with this? Maybe always to use has or is in the code?

if process_has_completed
  ...
end

if user_is_using_console
  ...
end

推荐答案

您必须询问 Matz 以获得权​​威答案.然而,

You'd have to ask Matz to get an authoritative answer. However,

  • Ruby 是一种无类型的编程语言,而像 finished? 这样的变量意味着一个特定的类型(布尔值),这在我看来有些矛盾.
  • 一个问题在某种程度上需要一个接收者(谁可以回答这个问题).一个方法必须有一个接收者(调用该方法的对象),所以问号是有意义的.另一方面,变量没有接收器,它只是一个容器.
  • Ruby is an untyped programming language and a variable like finished? would imply a specific type (boolean) which appears somewhat contradictory to me.
  • A question somewhat requires a receiver (who can answer the question). A method must have a receiver (the object the method is called on), so a question mark makes sense. A variable on the other hand has no receiver, it's a mere container.

这篇关于为什么变量名不能以`?`结尾而方法名可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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