, ( : @max, @min), , , . , , - .
, . :
@value = 0
def test
@value = 1
end
puts @value ==> 0
test
puts @value ==> 1
.
, Ruby , Ruby )
list = [4,6,10,7,1,2]
def maxmin(list)
f = list.shift
if list.empty? then
return f, f
end
mi, ma = maxmin(list)
if (f > ma) then
ma = f
elsif (f < mi)
min = f
end
return mi, ma
end
min, max = maxmin(list)
printf("max=#{max}, min=#{min}")
Your way of doing it is quite funny (love recursion), but it’s not very elegant, the performances are not really good, and besides, it is a bit confusing, which is far from the ruby vision.
list = [4,6,10,7,1,2]
def minmax(list)
max = list[0]
min = list[0]
list.each do |elem|
if elem > max then
max = elem
elsif elem < min
min = elem
end
end
return min, max
end
min, max = minmax(list)
printf("max=#{max}, min=#{min}")
It is a clearer version of your code, even if it is less cool. You can try these answers with global variables, this should be easy.
Obviously, from the perspective of Ruby, when you are done with this, you can use Array.max and Array.min.