What is the most short/elegant way of ending the current iteration
within a block? My first thought was that next' will break the iteration and last evaluated expr will be returned to the caller, but surprisinglynil’ is returned this way, so we have (Ruby 1.6.8):
[1,2].map {|i| next ‘b’ if i < 2; ‘a’}
=> [“b”, “a”]
Cheers
Dave
···
On Wednesday, Mar 12, 2003, at 23:17 US/Central, Wojciech Kaczmarek wrote:
What is the most short/elegant way of ending the current iteration
within a block? My first thought was that next' will break the iteration and last evaluated expr will be returned to the caller, but surprisingly nil’ is returned this way, so we have (Ruby 1.6.8):
What is the most short/elegant way of ending the current iteration
within a block? My first thought was that next' will break the iteration and last evaluated expr will be returned to the caller, but surprisingly nil’ is returned this way, so we have (Ruby 1.6.8):
Seems that `next ’ syntax is not available in 1.6.x.
···
On Thu, 13 Mar 2003 14:46:49 +0900, Dave Thomas wrote:
What is the most short/elegant way of ending the current iteration
within a block? My first thought was that next' will break the iteration and last evaluated expr will be returned to the caller, but surprisingly nil’ is returned this way, so we have (Ruby 1.6.8):
What is the most short/elegant way of ending the current iteration within a
block? My first thought was that next' will break the iteration and last evaluated expr will be returned to the caller, but surprisingly nil’ is
returned this way, so we have (Ruby 1.6.8):
[‘bar’,‘quux’].map {‘foo’; next; 42}
=> [nil, nil]
What about
[‘bar’,‘quux’].map {‘foo’}
Why do you need the “next”?
I can assure you I don’t need it in the above example :->
I assume you want to go trough the array, map values and omit some of
them. You can do
[‘bar’,‘quux’].map {|e| e == ‘bar’ ? nil : ‘foo’}.compact
[‘bar’,‘quux’].select{|e| e != ‘bar’ }.map{‘foo’}
That’s good, but let’s imagine the selection predicate as a
fatty-several-times-nested statement – it’d be convenient to leave block
with a proper value sooner in some simpler cases.
Anyway, the syntax I dream of is avalilable in 1.7.