Hacker News new | ask | show | jobs
by Alifatisk 302 days ago
The indent in your Ruby code is a bit weird. It should be like this

    class Mess
      def chaos(x)
        if x > 0
          [1, 2, 3].each do |i|
            case i
            when 1
              if i.odd?
                puts "odd"
              else
                puts "even"
              end
            when 2
              begin
                puts "trying"
              rescue
                puts "failed"
              end
            else
              puts "other"
            end
          end
        else
          puts "negative"
        end
      end
    end

I would have done it this way instead

    class Mess
      def chaos(x)
        if x > 0
          [1, 2, 3].each do |i|
            case i
            when 1
              puts i.odd? ? "odd" : "even"
            when 2
              puts "trying"
            else
              puts "other"
            end
          end
        else
          puts "negative"
        end
      end
    end
Or if you allow me to create a separate private method

    class Mess
      def chaos(x)
        return puts "negative" unless x > 0
    
        [1, 2, 3].each { |i| handle_item(i) }
      end

      private
      def handle_item(i)
        case i
        when 1 then puts(i.odd? ? "odd" : "even")
        when 2 then puts "trying"
        else        puts "other"
        end
      end
    end