Reputation: 46579
Should be an easy one. I thought, from reading this blog post that I could return something right after my next
command:
next "new value" if axis_range == "test"
What I'd really like to do is log the reason for the next on the same line:
next @logger.info('skipping this item because for fun') unless (elephants.size > 0)
I can't find any discussion of this usage of next
on ruby doc. The code certainly works. I realize I can do this with an unless
block but the that line of code is sooo concise.
Two questions:
next
a little odd and not 'ruby-ish'? Upvotes: 10
Views: 5424
Reputation: 80065
" Like the
return
andbreak
keywords,next
may be used alone, or it may be followed by an expression or a comma-separated list of expressions. Whennext
is used in a loop, any values followingnext
are ignored. In a block however the expression or expressions become the "return value" of theyield
statement that invoked the block." (The Ruby Programming Language, David Flanagan & Yukihiro Matsumoto, 2008, page 150)
The book gives this example:
squareroots = data.collect do |x|
next 0 if x < 0 # return 0 for negative values
Math.sqrt(x)
end
and this alternative:
squareroots = data.collect do |x|
if (x < 0) then 0 else Math.sqrt(x) end
end
Upvotes: 23
Reputation: 31726
I wouldn't inherently have a problem with it unless it was right in the middle of a lot of other complicated code (I try to average 2 LOC per method, usually one or two that are 4-8 lines long, and a bunch that are only one line, averaging out).
If the code is long and difficult to understand, I've had a lot of success pulling the method out into its own object. I just have the method instantiate some object that does its task and ask it for the result, then the code can be much simpler, often reducing the loop to just a line or two and allowing it to have a method that does this logging, which you could then handle with a simple call to log_error or whatever name you think is appropriate.
These days I consider complex procedural methods to be a smell that there is an object gestating in this method.
Upvotes: 0
Reputation: 43815
My first impression is that it's fairly self evident what the next
keyword does within the context of a loop - that's a good thing. The fact that "new value"
is a result of next "new value"
is a bit of a stretch, but I can get there.
What throws me off is that next @logger.info('skipping this item because for fun')
would likely be hard to understand. It's really not evident that the result of the info
call is going to be returned by next
and I believe a lot of devs would get thrown off by it.
While the code may be more concise, it's difficult to understand. I'd either comment on what the code is doing or go with something else.
Nevertheless good call on your two questions. I would be happy to be a developer maintaining your code with that type of mindset!
Upvotes: 0