【问题标题】:Ruby equivalent operators at "OrElse" and "AndAlso" of Vb.netVb.net 的 "OrElse" 和 "AndAlso" 的 Ruby 等效运算符
【发布时间】:2011-06-13 15:29:14
【问题描述】:

Ruby 中有类似于 VB.NET 中的“OrElse”和“AndAlso”的运算符?

例如在 Ruby 中,当 active_record 为 nil 时会引发 NoMethodError 异常:

if active_record.nil? || active_record.errors.count == 0
     ...
end

在 VB.net 中我可以做到:

 If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End

这不会产生异常,因为它只检查了第一个表达式

【问题讨论】:

  • 代码中的active_record 是实际的库,还是一个示例 active_record 对象?
  • 在这个例子中active_record是一个可以为nil的对象
  • 不知道为什么你会抚摸你的短语。关于最后一个,正确的是在 VB.NET 中,仅当第一个表达式为假时才评估第二个表达式。 This is short circuit operation,同样的事情发生在 Ruby &&||

标签: ruby operators


【解决方案1】:

在这种情况下,不会引发异常(因为只会计算 || 中的第一项)。但是,您可能有兴趣阅读 ActiveSupport 中有关 Object#try 的内容,这在处理可能为 nil 的对象时会很有帮助。

【讨论】:

  • 你是对的。我的代码有问题。只评估第一项。
【解决方案2】:

Ruby ||short circuit evaluation 运算符,因此它应该只评估第一个条件,因此您的 if 不应引发任何异常。

我假设 active_record.nil? 返回布尔值 true

【讨论】:

    【解决方案3】:

    在 ruby​​ 中,nil 和 undefined 之间有很大的区别。考虑到以下内容,来自 IRB:

    ruby-1.9.2-p0 :002 > active_record
    NameError: undefined local variable or method `active_record' for main:Object
        from (irb):2
        from /Users/jed/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
    ruby-1.9.2-p0 :003 > active_record = nil
     => nil 
    ruby-1.9.2-p0 :004 > active_record.class
     => NilClass 
    ruby-1.9.2-p0 :006 > active_record.nil?
     => true 
    

    因此,nil 的对象是 NilClass 的一个实例,因此响应消息 nil? 将返回 true,但不声明变量(如在您的代码中)Ruby 不知道您在调用什么。

    这里有几个选项:

    Ruby 的|| 操作符是严格操作符,而or 关键字不那么严格,所以我不知道vb 操作与这两个或流选项相比在哪里。

    您可以使用一个名为“andand”的简洁小宝石

    require 'andand'
    active_record.andand.errors.count == 0
    

    但是,通常当您在rails中处理这种情况时,您会使用另一种方法来确定上述情况,请考虑:

    @post = Post.new(:my_key => "my value") #=> an ActiveRecord object
    if @post.valid?
      # do something meaningful
    else
      puts @post.errors.full_messages.to_sentence
    end
    

    如果你的意思是根据它是否可能未定义来分配一些东西,你会想要使用记忆:

    @post ||= Post.new 
    

    如果未定义将声明对象或使用现有对象

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2010-09-08
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多