Ruby check if nil before calling method

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

提交回复
热议问题