Macsika Imoh Macsika Imoh - 10 days ago 6
Ruby Question

ruby program with list

I am trying to get a list of colors to print after the color blue without using the index. I did this

colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]

colors.each { |item| print item if item > "Blue" }


but the output is this


Red Green Purple White


Does anyone know why?

Answer

The question "Why" is already answered in the comment of davidhu2000:

Because you are printing all items that is alphabetically after blue

If you don't want to use the index, then you can use a solution with a help variable:

colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]

blue_found  = false
colors.each { |item| 
  if blue_found
    print item
  else
      blue_found ||= item == "Blue" 
  end
}

If you prefer a one-liner you could use

  blue_found ? (print item) :  (blue_found ||= item == "Blue" )

Another possibility:

colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]

blue_found  = false
colors.each { |item| 
  print item if blue_found 
  blue_found ||= item == "Blue" 
}

I was curious, why you don't want to use the index, so I made some more research outside your question.

The solution with index would be:

colors.each_with_index { |item,i| 
  print item if i > colors.index("Blue")
}

The index-method may need some more runtime. To test it, I made a little benchmark:

colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]

require 'benchmark'

TEST_LOOPS = 10_000

def action(item)
  #Just a no-action.
end

Benchmark.bm(10) {|b|

  b.report('test/variable') {
   TEST_LOOPS.times { 
    blue_found  = false
    colors.each { |item| 
      action(item) if blue_found 
      blue_found ||= item == "Blue" 
    }
   }            #Testloops
  }             #b.report

  b.report('test/index') {
   TEST_LOOPS.times { 
    colors.each_with_index { |item,i| 
      action(item) if i > colors.index("Blue")
    }
   }            #Testloops
  }             #b.report

} #Benchmark

The result:

                  user     system      total        real
test/variable  0.110000   0.000000   0.110000 (  0.114006)
test/index     0.218000   0.000000   0.218000 (  0.216013)

So the version with a help variable is (as expected) faster.

(Disclaimer: I made not many thoughts for faster solutions. So maybe there is a more efficient way).