【问题标题】:What is the 'end.new' in Ruby for? Why not just use 'end' on it's ownRuby 中的“end.new”有什么用?为什么不单独使用“结束”
【发布时间】:2019-05-09 08:28:21
【问题描述】:

我遇到了this question,@Kris 的回答是这样的:

end.new

这里:

  subject do
    Class.new do
      include ActiveModel::Validations    
      attr_accessor :email
      validates :email, email: true
    end.new
  end

我以前没有见过,也找不到其他例子或解释。

为什么不自己“结束”,像这样:

  subject do
    Class.new do
      include ActiveModel::Validations    
      attr_accessor :email
      validates :email, email: true
    end
  end

有什么区别?

【问题讨论】:

  • Class.new 将返回一个类。 Class.new.new 将返回该类的一个实例。
  • @ndnenkov 哦,这很酷,谢谢,你的评论马上就明白了 :)

标签: ruby


【解决方案1】:

首先你需要明白你可以在end上链接语句,例如

[1,2,3,4,5].select do |num|
  i % 2 == 0
end.map do |num|
  "#{num} is even"
end.each do |str|
  puts str
end

接下来,要了解您的示例,您需要了解什么是“匿名”类。

你可以正常定义这个类:

class MyClass
  include ActiveModel::Validations    
  attr_accessor :email
  validates :email, email: true
end

您将定义一个 global MyClass 变量来引用 class。当然,你也可以拨打MyClass.new获取实例。

异常类块Class.new do 是同一件事,但它没有为类定义全局标识符。相反,要获得类的句柄,您必须为 Class.new do .. end 表达式的结果分配一个变量。

因此,如果您了解 Class.new do ... end 返回一个类,并且您可以在任何类上调用 .new,那么您可以执行类似于您问题中的代码的操作:

klass = Class.new { def foo; "bar"; end }
klass.new.foo # => "bar"

# or ...
Class.new { def foo; "bar"; end }.new.foo # => "bar"

do ... end{} 的多行版本,用于定义块

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 2016-04-15
    • 2014-11-12
    • 2021-08-22
    • 1970-01-01
    • 2018-01-12
    • 2011-03-13
    相关资源
    最近更新 更多