新手问题 Ruby 调用方法不写括号只写空格逗号有什么副作用吗

tablecell · 2020年08月07日 · 最后由 lanzhiheng 回复于 2020年08月07日 · 1732 次阅读

括号的好处是可以嵌套调用 目前想到的就是这个

没有什么副作用。主要是可以让用户写出真正的方法链

0> "hello".methods.grep /str/
=> [:strip, :rstrip, :to_str, :lstrip, :strip!, :lstrip!, :rstrip!]

一般建议带参数的时候都带上括号这样代码更易读。在类中调用方法除外,在 Rails 里一般调用类方法都会采用类似于宏定义的写法

class Post < ApplicationRecord
  belongs_to :category
  validates :title, presence: true
end

其实写成这样也没差,只是没人会这么去写

class Post < ApplicationRecord
  belongs_to(:category)
  validates(:title, presence: true)
end
lanzhiheng 回复

如果是嵌套的调用 比如 print(funcall(param)) 这种的只能拆成两行代码了吗?

tablecell 回复

不用啊。这样写都行print method :dup 只是可读性不好一般建议写成这样print method(:dup)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号