David Haley
David Haley

Reputation: 41

High & Low Numbers From A String (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

Upvotes: 3

Views: 1407

Answers (2)

Simon Fromme
Simon Fromme

Reputation: 3174

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]

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

Using sort would be inefficient for big arrays. Instead, use Enumerable#minmax:

numbers.split.map(&:to_i).minmax
# => [-214, 542]

Or use Enumerable#minmax_by if you like result to remain strings:

numbers.split.minmax_by(&:to_i)
# => ["-214", "542"]

Upvotes: 2

Related Questions