1

So I am pushing some elements on my array like this:

upd_city_list << [ j.children[0].text.strip!.gsub(/\s+\W/, ''), j.children[1].text, j.children[1][:href] ]

The above is in an iterator (hence the use of j).

The issue is that from time to time, the j.children[0].text turns up as nil, and Ruby doesn't like that.

I could add a bunch of if statements before this assignment, but that seems a bit inelegant to me.

How do I handle nil cases in this situation in an elegant way?

One possible solution is, when there is a nil value, just push the string none onto the array....but what would that look like?

Thanks.

Edit1:

This is the error I am getting:

NoMethodError: private method ‘gsub’ called for nil:NilClass
4

6 に答える 6

2

j.children[0].text.strip!次の2つのうちの1つに置き換える必要があります。

(j.children[0].text || 'none').strip

また

j.children[0].text.to_s.strip

もちろん、テキストがnilの場合、これらは異なる効果をもたらします。あなたの実際の問題はstrip!nilを返すことであり、それはエラーメッセージから明らかなはずだったと思います。

于 2012-05-26T08:00:45.753 に答える
2

本当の問題はstrip!、文字列に変更がない場合に nil を返すことです。あなたのtextメソッド文字列を返しています。あなたのstrip!メソッドはnilを返しています。なぜこれを行うのかわかりません。私も嫌いです。

strip!に変更するだけで、この問題のケースはなくなりますstrip

より一般的な意味では、配列を返すオブジェクトを作成できます。のこぎりを変えたくないのですが(私が推測しているのは)のこぎりですが、結果として生じる列車の残骸を隠すために何かで包むことができます.

于 2012-05-26T16:53:31.407 に答える
1

これは、nullオブジェクトプログラミングパターンを使用する場合に当てはまる可能性があります。Nilは適切なnullオブジェクトではありません。ここここを読んでみてください。ヌルオブジェクトはエレガントな方法です。

于 2012-05-26T07:58:42.243 に答える
0

レール環境にいる場合は、次のtry方法を試すことができます: https://github.com/rails/rails/blob/82d41c969897cca28bb318f7caf301d520a2fbf3/activesupport/lib/active_support/core_ext/object/try.rb#L50

于 2012-05-26T08:23:24.303 に答える
0

nil or a_stringになりますa_string

それでどうですか(j.children[0].text or 'none')

于 2012-05-26T07:50:26.277 に答える
0

レールを使用している場合、これは try メソッドの優れた使用方法です。

また、ストリップと gsub が冗長であるようです。この実装を検討してください:

descriptive_name_1 = j.children[0].text.try(:strip)
descriptive_name_2 = j.children[1].text
descriptive_name_3 = j.children[1][:href]
updated_city_list << [ descriptive_name_1 , descriptive_name_2, descriptive_name_3 ]

試さない

descriptive_name_1 = j.children[0].text.to_s.strip 
descriptive_name_2 = j.children[1].text
descriptive_name_3 = j.children[1][:href]
updated_city_list << [ descriptive_name_1 , descriptive_name_2, descriptive_name_3 ]
于 2012-05-26T08:06:29.100 に答える