I wrote the following Ruby code:
def myItems
if @item1
yield @item1
end
if @item2
yield @item2
end
end
Now I tried to use:
myItems.each do |item|
puts item
end
However, when both @item1 and @item2 are nil, I get the error:
Error: #<NoMethodError: undefined method `each' for nil:NilClass>.
I would expect an equivalent to “yield break” in C# to prevent this. Does anyone know how this works in Ruby?
It’s hard to tell what you are trying to do, but I think you want simply:
Your current code is assuming that the return value of
myItemsis an enumerable (e.g. an array), and under no circumstance (even if your@items are notnil) is that the return value.Alternatively, do either this:
…or this:
Note: I’ve used
camelCasemethod names because that’s what you have originally, but note that it’s idiomatic in Ruby to usesnake_caseinstead.Note 2: storing multiple similar items as instance variables instead of as a collection seems less useful than storing the collection itself. However, without knowing your data I cannot suggest a better way to represent this.