-2

I am currently learning Ruby and for the sake of my life I cannot find a solution to this:

Return the greatest value from an array of numbers.

Input: [5, 17, -4, 20, 12] Output: 20

Can anyone help me out with this and explain why they used their solution?

thank you.

Cholis
  • 61
  • 1
  • 2
  • 5
  • It's probably best to go through a tutorial which would cover these types of things. – Sagar Pandya Apr 13 '19 at 03:35
  • What have you tried? What is the code you are having trouble with? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Please, provide a [mcve]. – Jörg W Mittag Apr 13 '19 at 06:51

2 Answers2

1

Just use Array#max

[5, 17, -4, 20, 12].max # => 20

If you learn and want to find it manually you can use loops.

For example

max_value = -Float::INFINITY

for item in [5, 17, -4, 20, 12] do
  max_value = item if item > max_value
end

max_value # => 20

In this loop, you check all the elements of the array one by one and assign the value max_value to the value that is currently maximal.

But in Ruby it's better to use each for this purpose

max_value = -Float::INFINITY

[5, 17, -4, 20, 12].each { |item| max_value = item if item > max_value }

max_value # => 20

Even as an idea, for example, here's the way

[5, 17, -4, 20, 12].sort.last # => 20

As you understand it all Enumerable and Array methods. In Ruby it is a very powerful tool.

mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • 3
    Have you lost your mind? You are teaching a Ruby newbie to use `for` loops!! – Cary Swoveland Apr 13 '19 at 00:24
  • 1
    @CarySwoveland, why are you so angry? It's just example :) I've added `each` – mechnicov Apr 13 '19 at 00:32
  • 1
    Probably because in any code review a Rubyist would say “rewrite this `for` loop to be anything else.” We don’t like them. We don’t use them. We don’t teach people new to the language to use them. There are better solutions. – anothermh Apr 13 '19 at 04:14
0

This is the way to remove characters from array and find max.

[1,2,3,-4,'a'].map(&:to_i).max
Kishor Vyavahare
  • 799
  • 1
  • 8
  • 15