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

tablecell · August 07, 2020 · Last by lanzhiheng replied at August 07, 2020 · 1733 hits

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

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

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
Reply to lanzhiheng

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

Reply to tablecell

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

You need to Sign in before reply, if you don't have an account, please Sign up first.