Ruby check if nil before calling method

后端 未结 11 2227
眼角桃花
眼角桃花 2020-12-25 09:52

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

H

相关标签:
11条回答
  • 2020-12-25 10:39

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

    0 讨论(0)
  • 2020-12-25 10:43

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

    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.

    So in your case you would do:

    s = "12345 "
    s &&= s.strip
    
    0 讨论(0)
  • 2020-12-25 10:44

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

    s&.strip
    

    If s is nil, this expressions returns nil instead of raising NoMethodError.

    0 讨论(0)
  • 2020-12-25 10:44

    You could simply do this

    s.try(:strip)
    
    0 讨论(0)
  • 2020-12-25 10:46

    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.

    0 讨论(0)
提交回复
热议问题