Ruby check if nil before calling method

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

提交回复
热议问题