Ruby 在调用方法之前检查是否为 nil

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12425465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:25:55  来源:igfitidea点击:

Ruby check if nil before calling method

rubynull

提问by user1513388

I have a string in Ruby on which I'm calling the strip method to remove the leading and trailing whitespace. e.g.

我在 Ruby 中有一个字符串,我在该字符串上调用 strip 方法来删​​除前导和尾随空格。例如

s = "12345 "
s.strip

However if the string is emptynilI get the following error.

但是,如果字符串为空,则会出现nil以下错误。

NoMethodError: undefined method `strip' for nil:NilClass

I'm using Ruby 1.9 so whats the easiest way to check if the value is nilbefore calling the strip method?

我正在使用 Ruby 1.9,那么nil在调用 strip 方法之前检查值是否是最简单的方法是什么?

Update:

更新:

I tried this on an element in an array but got the same problem:

我在数组中的一个元素上尝试过这个,但遇到了同样的问题:

data[2][1][6].nil? ? data[2][1][6] : data[2][1][6].split(":")[1].strip

回答by user513951

Ruby 2.3.0added a safe navigation operator(&.) that checks for nil before calling a method.

Ruby 2.3.0添加了一个安全导航操作符( &.),它在调用方法之前检查 nil。

s&.strip

It will return nilif sis nil, rather than raising NoMethodError.

nil如果snil,它将返回,而不是提高NoMethodError

回答by megas

You can use method tryfrom ActiveSupport (Rails library)

您可以使用tryActiveSupport(Rails 库)中的方法

gem install activesupport

require 'active_support/core_ext/object/try'
s.try(:strip)

or you can use my gem tryitwhich gives extra facilities:

或者你可以使用我的 gem tryit提供额外的便利:

gem install tryit

s.try { strip }

回答by Michael Kohl

If you don't mind the extra object being created, either of these work:

如果您不介意创建额外的对象,则以下任一方法都有效:

"#{s}".strip
s.to_s.strip

Without extra object:

没有额外的对象:

s && s.strip
s.strip if s

回答by lukad

I guess the easiest method would be the following:

我想最简单的方法如下:

s.strip if s

回答by ksol

ActiveSupportcomes with a method for that : try. For example, an_object.try :stripwill return nilif an_objectis nil, but will proceed otherwise. The syntax is the same as send. Cf active_support_core_extensions.html#try.

ActiveSupport附带一个方法:try。例如,如果为 nilan_object.try :strip将返回,否则将继续。语法与. 参见active_support_core_extensions.html#trynilan_objectsend

回答by 3limin4t0r

I'd opt for a solution where scan never be nilto start with.

我会选择一个s永远无法nil开始的解决方案。

You can use the ||operator to pass a default value if some_methodreturns a falsy value:

||如果some_method返回假值,您可以使用运算符传递默认值:

s = some_method || '' # default to an empty string on falsy return value
s.strip

Or if sis already assigned you can use ||=which does the same thing:

或者,如果s已经分配,​​您可以使用||=which 做同样的事情:

s ||= '' # set s to an empty string if s is falsy
s.strip

Providing default scenario's for the absence of a parameters or variables is a good way to keep your code clean, because you don't have to mix logic with variable checking.

为缺少参数或变量提供默认方案是保持代码干净的好方法,因为您不必将逻辑与变量检查混合在一起。

回答by sawa

If you want to avoid the error that appears in the question:

如果要避免问题中出现的错误:

s.to_s.strip

回答by Victor Moroz

Method which works for me (I know, I should never pollute pristine Objectspace, but it's so convenient that I will take a risk):

对我有用的方法(我知道,我永远不应该污染原始Object空间,但它太方便了,我会冒险):

class Object
  def unless_nil(default = nil, &block)
    nil? ? default : block[self]
  end
end

p "123".unless_nil(&:length) #=> 3
p nil.unless_nil("-", &:length) #=> "-"

In your particular case it could be:

在您的特定情况下,它可能是:

data[2][1][6].unless_nil { |x| x.split(":")[1].unless_nil(&:strip) }

data[2][1][6].unless_nil { |x| x.split(":")[1].unless_nil(&:strip) }

回答by Eugene

Simply put:

简单的说:

s = s.nil? ? s : s.strip

Tl;dr Check if s is nil, then return s, otherwise, strip it.

Tl;dr 检查 s 是否为零,然后返回 s,否则,将其剥离。

回答by tanius

To complete the options shown here, there is the "Existence Check Shorthand", recommended in the Ruby Style Guide:

要完成此处显示的选项,请使用 Ruby 样式指南中推荐的“存在检查速记” :

Use &&=to preprocess variables that may or may not exist. Using &&=will change the value only if it exists [means, is not nil], removing the need to check its existence with if.

使用&&=预处理的变量,可能会或可能不存在。&&=仅当值存在 [意味着,不是nil] 时,使用才会更改值,从而无需使用if.

So in your case you would do:

所以在你的情况下,你会这样做:

s = "12345 "
s &&= s.strip