Sorting with control flow


#1



can you check my code?


def alphabetize (arr, rev=false)
    arr.sort!
    if rev == true
        arr.reverse!
    end
end
numbers = [5,1,3,8]

alphabetize (numbers)
puts numbers

Replace this line with your code.

`


#2

@jkm345,

def alphabetize (arr, rev=false)
    arr.sort!
    if rev == true
        arr.reverse!
    end
end
numbers = [5,1,3,8]

alphabetize (numbers,true)
puts numbers.map(&:inspect).join(',')
alphabetize (numbers)
puts numbers.map(&:inspect).join(',')

which gives the output

8,5,3,1
1,3,5,8

http://stackoverflow.com/questions/3500814/ruby-array-to-string-conversion


#3

I get this error message:
(ruby):10: syntax error, unexpected ',', expecting ')'
alphabetize (numbers,true)

can you please help?


#4

@jkm345,

Please give the full code you are using....


#5

I get this error message when I try it. can you help?

(ruby):9: syntax error, unexpected ',', expecting ')'
alphabetize (numbers,true)

def alphabetize (arr, rev=false)
    arr.sort!
    if rev == true
        arr.reverse!
    end
end

numbers = [5,1,3,8]

alphabetize (numbers,true)
puts numbers.map(&:inspect).join(',')
alphabetize (numbers)
puts numbers.map(&:inspect).join(',')

#6

I attached the code on the last reply (after the one with the error code)


#7

here's the code:

def alphabetize(arr, rev=false)
  if rev
    arr.sort { |item1, item2| item2 <=> item1 }
  else
    arr.sort { |item1, item2| item1 <=> item2 }
  end
end

numbers = [5,1,3,8]

alphabetize (numbers,true)
puts numbers.map(&:inspect).join(',')
alphabetize (numbers)
puts numbers.map(&:inspect).join(',')

#8

sorry I put the wrong code in the previous reply it should be as follows:

def alphabetize (arr, rev=false)
    arr.sort!
    if rev == true
        arr.reverse!
    end
end

numbers = [5,1,3,8]

alphabetize (numbers,true)
puts numbers.map(&:inspect).join(',')
alphabetize (numbers)
puts numbers.map(&:inspect).join(',')