Ruby check if nil before calling method

2020-02-20 06:11发布

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

s = "12345 "
s.strip

However if the string is empty I get the following error.

NoMethodError: undefined method `strip' for nil:NilClass

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

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

标签: ruby null
10条回答
戒情不戒烟
2楼-- · 2020-02-20 07:16

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

s&.strip

It will return nil if s is nil, rather than raising NoMethodError.

查看更多
何必那么认真
3楼-- · 2020-02-20 07:17

ActiveSupport comes with a method for that : try. For example, an_object.try :strip will return nil if an_object is nil, but will proceed otherwise. The syntax is the same as send. Cf active_support_core_extensions.html#try.

查看更多
手持菜刀,她持情操
4楼-- · 2020-02-20 07:17

You could simply do this

s.try(:strip)
查看更多
Animai°情兽
5楼-- · 2020-02-20 07:18

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
查看更多
登录 后发表回答