Ruby Ruby 的语法糖 * 号你还知多少

lyfi2003 · 2012年10月09日 · 最后由 tumayun 回复于 2012年10月26日 · 7259 次阅读

我们都知道 *arg 是展开参数的,但下面不带参数的 * 是什么含义?

# Overwrite render_to_string because body can now be set to a rack body.
def render_to_string(*) # 这个 * 代表哪门子含义
  if self.response_body = super
    string = ""
    response_body.each { |r| string << r }
    string
  end
ensure
  self.response_body = nil
end

我个人实验,感觉目的就是不关心传来的参数,全部送给 super 处理,你认为是这样么?

不明,但感觉这部分触及到了 Ruby 语法的阴暗面~

#3 楼 @5long #2 楼 @rociiu https://github.com/rubyspec/rubyspec/blob/master/language/def_spec.rb#L35 补充这个。

基本可以确定这种写法:

  1. 可以支持任意参数
  2. 使用 super 时,将参数传递给 super; 否则无视各参数。
  1. *args是一样的,只是因为不需要使用 args 就省略了
  2. suppersupper()是有区别的,但是这个特性和*是没关系的,你被supper误导了。

#5 楼 @hooopo thx, super 是这样,多谢指正。对我们来说是比较方便,对 Ruby解释器 还是需要解析的。

奇怪的用法能不用就不用吧。不然太另类了。

看到这个用法的确有点吃惊...

  • 叫做 splat 操作符,在定义一个方法形参的情景,它明确的告诉解释器,我接受任意多个参数, 并且将这些参数作为一个数组, 传入方法定义内'. 既然 * 后面没有提供一个明确的数组名称, 那就是作为空名称的数组` 被传入,这也就意味着,你输入任何参数,无论多少个,都作为一个没名字的数组,其实就是忽略所有的参数

可惜不是所有的字符都可以这样,我刚刚试了下

def hello(&)         # => 期望这个方法无法接受 任何代码块.
 end

不过不成功,因为语法本身就是错误的。: )

#8 楼 @zw963 正如 @hooopo 所述,使用在 super 中是非常不错的。

你说这个也有些意思,可以尝试提交 ruby-core 团队~

有牛人总结过 ruby 里面那些地方的省略容易造成疑惑和错误吗

应该就是这个意思,自己不用,给上面用

Folks sometimes use a splat to specify arguments that are not used by the method (but that are perhaps used by the corresponding method in a superclass. (Note that in this example we call super with no parameters. This is a special case that means “invoke this method in the superclass, passing it all the parameters that were given to the original method.”)

class Child < Parent def do_something(*not_used) # our processing super end end

In this case, you can also leave off the name of the parameter and just write an asterisk:

class Child < Parent def do_something(*) # our processing super end end

  • Programming Ruby 1.9 The Pragmatic Programmers' Guide Page 139

@hooopo supersuper() 有什么区别?

掉坑里了,super是关键字,不是方法

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