Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is returning a value from 'next' a bad idea?

Tags:

ruby

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:

  • Is there a better document somewhere?
  • Is this usage of next a little odd and not 'ruby-ish'?
like image 783
jcollum Avatar asked Mar 05 '12 03:03

jcollum


1 Answers

" Like the return and break keywords, next may be used alone, or it may be followed by an expression or a comma-separated list of expressions. When next is used in a loop, any values following nextare ignored. In a block however the expression or expressions become the "return value" of the yield 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 
like image 172
steenslag Avatar answered Sep 24 '22 04:09

steenslag