Search code examples
rubycomparison-operators

NoMethodError in Ruby with Comparison Statement


I decided to start learning a bit of Ruby and went to attempt an insertion sort version in Ruby (2.3.0). However when my program checks to see the position and whether to swap values it returns a NoMethodError for '>'. More specifically:

./rubyInsertSort.rb:28:in `block in sort': undefined method `>' for 1..4:Range (NoMethodError)
from ./rubyInsertSort.rb:26:in `each'
from ./rubyInsertSort.rb:26:in `sort'
from ./rubyInsertSort.rb:22:in `main'
from ./rubyInsertSort.rb:40:in `<main>'

Here is the code for the sorting method:

def sort(input, valueAmount)
  for i in 1..valueAmount
    j = i
    while j > 0 and input[j - 1] > input[j]
      input[j], input[j - 1] = input[j - 1], input[j]
      j += -1           
    end
  end

  #Output loop
  for i in 1..valueAmount
    puts "Sort Value #{i} = #{input[i]}"    #Outputs the sorted array to the console
  end
end

I know this is probably something trivial and really simple but I can't find a question on here or elsewhere with a solution and any help would be appreciated!


Solution

  • Modified your version

    def sort(input, valueAmount)
      for i in 1...valueAmount  # Added a dot
        j = i
        while j >= 0 and input[j - 1] > input[j]  # >= instead of >
          input[j], input[j - 1] = input[j - 1], input[j]
          j += -1
        end
      end
    
      #Output loop
      for i in 0...valueAmount  # Added a dot
        puts "Sort Value #{i} = #{input[i]}"    #Outputs the sorted array to the console
      end
    end
    

    And here is my version (without output)

    def insertion_sort!(ary)
      return ary if ary.size < 2
      1.upto(ary.size - 1) do |i|
        i.downto(0) do |j|
          break if ary[j - 1] <= ary[j]
          ary[j - 1], ary[j] = ary[j], ary[j - 1]
        end
      end
      ary
    end