Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High & Low Numbers From A String (Ruby)

Tags:

ruby

Good evening,

I'm trying to solve a problem on Codewars:

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Example:

high_and_low("1 2 3 4 5")  # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"

Notes:

All numbers are valid Int32, no need to validate them. There will always be at least one number in the input string. Output string must be two numbers separated by a single space, and highest number is first.

I came up with the following solution however I cannot figure out why the method is only returning "542" and not "-214 542". I also tried using #at, #shift and #pop, with the same result.

Is there something I am missing? I hope someone can point me in the right direction. I would like to understand why this is happening.

def high_and_low(numbers)
    numberArray = numbers.split(/\s/).map(&:to_i).sort
    numberArray[-1]
    numberArray[0]
end

high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

EDIT

I also tried this and receive a failed test "Nil":

def high_and_low(numbers)
  numberArray = numbers.split(/\s/).map(&:to_i).sort
  puts "#{numberArray[-1]}" + " " + "#{numberArray[0]}"
end
like image 345
David Haley Avatar asked May 27 '26 16:05

David Haley


1 Answers

When omitting the return statement, a function will only return the result of the last expression within its body. To return both as an Array write:

def high_and_low(numbers)
    numberArray = numbers.split(/\s/).map(&:to_i).sort
    return numberArray[0], numberArray[-1]
end

puts high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
# => [-214, 542]
like image 177
Simon Fromme Avatar answered May 30 '26 03:05

Simon Fromme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!