Ruby check if nil before calling method

后端 未结 11 2226
眼角桃花
眼角桃花 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:19

    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.

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

    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
    
    0 讨论(0)
  • 2020-12-25 10:24

    I guess the easiest method would be the following:

    s.strip if s
    
    0 讨论(0)
  • 2020-12-25 10:29

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

    s.to_s.strip
    
    0 讨论(0)
  • 2020-12-25 10:31

    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 }
    
    0 讨论(0)
  • 2020-12-25 10:37

    Simply put:

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

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

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