Forum: Ruby How can I do array program in different way?

1eb28f3c91b0a7b8bfb1a72cfa8befaa?d=identicon&s=25 Jaimin Pandya (jaimin)
on 2014-04-25 06:47
Attachment: array.rb (136 Bytes)
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[8]
     max = i
     end
  end
puts "maximum element of array is: #{max}"

In above program, If I do not want to use a[8] which i used in "if
i>a[8]" this code.

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

Kind regard.
55e8441972b0e0740e34161a493e902d?d=identicon&s=25 Gianfranco Bozzetti (gfb)
on 2014-04-25 10:03
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
1eb28f3c91b0a7b8bfb1a72cfa8befaa?d=identicon&s=25 Jaimin Pandya (jaimin)
on 2014-04-25 11:06
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.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (robert_k78)
on 2014-04-25 12:10
Jaimin Pandya wrote in post #1144021:

> Is it possible without using a[8]? 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
09ab9b19c6f92c76ab6b023244b820fd?d=identicon&s=25 Patrick Stauch (costauchy)
on 2014-04-25 17:40
Jaimin Pandya 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.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.