Wednesday, May 29, 2013

ruby: skipping elements in iteration cycle

Lets we have this situation:

[7, 2, 3, "a", "b", "c"].sort
ArgumentError: comparison of Fixnum with String failed
from (irb):1:in `sort'
from (irb):1


We want to sort only integer values.

The solution is using reject statement:

[7, 2, 3, "a", "b", "c"].reject{ |x| x.to_i == 0 }.sort
 => [2, 3, 7]

No comments:

Post a Comment