 How can I do array program in different way?

I write following program to find maximum element from array.

a = [15,2,34,3,4,6,8,65,43,23]
for i in a
puts i
if i>a
max = i
end
end
puts “maximum element of array is: #{max}”

In above program, If I do not want to use a which i used in “if
i>a” this code.

Is it possible without using a? if yes then How can I do it?

Kind regard.

See the following snippet:

arymax.rb Find the msx value for an array of integers

a = [15,2,34,3,4,6,8,65,43,23]
a_max=0
a.each { |x| a_max=x if(x > a_max) }
p a.inspect
p “Max value is #{a_max}”
END
Output:
ruby arymax.rb
“[15, 2, 34, 3, 4, 6, 8, 65, 43, 23]”
“Max value is 65”

hth gfb

Gianfranco Bozzetti wrote in post #1144051:

See the following snippet:

arymax.rb Find the msx value for an array of integers

a = [15,2,34,3,4,6,8,65,43,23]
a_max=0
a.each { |x| a_max=x if(x > a_max) }
p a.inspect
p “Max value is #{a_max}”
END
Output:
ruby arymax.rb
“[15, 2, 34, 3, 4, 6, 8, 65, 43, 23]”
“Max value is 65”

Thank you very much.

Kind regards.

Jaimin P. wrote in post #1144021:

Is it possible without using a? if yes then How can I do it?

irb(main):002:0> a = [15,2,34,3,4,6,8,65,43,23]
=> [15, 2, 34, 3, 4, 6, 8, 65, 43, 23]
irb(main):003:0> a.inject {|a,b| a > b ? a : b}
=> 65

Jaimin P. wrote in post #1144021:

I write following program to find maximum element from array.

a = [15,2,34,3,4,6,8,65,43,23]

puts “The maximum element in the array is #{a.max}.” #a.max=65

Though I really like the .inject method Robert wrote if you were just
looking for some ruby practice.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.