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 06:58

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

s.to_s.strip
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-20 07:00

I'd opt for a solution where s can never be nil to start with.

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

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

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

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.

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

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

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) }

查看更多
Juvenile、少年°
5楼-- · 2020-02-20 07:10

You can use method try from ActiveSupport (Rails library)

gem install activesupport

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

or you can use my gem tryit which gives extra facilities:

gem install tryit

s.try { strip }
查看更多
劫难
6楼-- · 2020-02-20 07:12

I guess the easiest method would be the following:

s.strip if s
查看更多
戒情不戒烟
7楼-- · 2020-02-20 07:12

Simply put:

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

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

查看更多
登录 后发表回答