[ruby-core:62819] [ruby-trunk - Feature #9867] Introduce each/else block into ruby

From: lukasz.strzebinczyk@...
Date: 2014-05-28 09:57:33 UTC
List: ruby-core #62819
Issue #9867 has been updated by Łukasz Strzebińczyk.


I came up with this idea after some study on http://handlebarsjs.com/. In that case, the 'else' block is invoked when collection is empty.
This would have clear translation for Array or Hash, however I'm having a problem trying to define this in more global matter.
As for the example, this is quite common case when printing out some collection in erb or any other:

  <% if @rooms.any?%>
    <% @rooms.each do |room| %>
      <%= render "room", room: room %>
    <% end %>
  <% else %>
    There are no rooms created yet. <%= link_to "Create first room!", new_room_path %>
  <% end %>


----------------------------------------
Feature #9867: Introduce each/else block into ruby
https://bugs.ruby-lang.org/issues/9867#change-46943

* Author: Łukasz Strzebińczyk
* Status: Feedback
* Priority: Low
* Assignee: Yukihiro Matsumoto
* Category: syntax
* Target version: 
----------------------------------------
Hi

Code like this happens quite often:

    if array.any?
      array.each do |elem|
        some_work
      end
    else
      do_something_else
    end

I was thinking if it was possible, to introduce syntax like this:

    array.each do |elem|
      some_work
    else
      do_something_else
    end

where code in else would fire if array is empty. This would simplify a lot of code nicely and would be completely backwards compatible. Is that a good idea?



-- 
https://bugs.ruby-lang.org/

In This Thread

Prev Next