Get a variable whose value is the maximum in the array

If I have an array of variables in Ruby:

a = 4
b = 7
c = 1

array = [a, b, c]

How to access the variable name with the highest value? (In this example b) I want to get a link to the element with the highest value so that I can subsequently manipulate it:

b += 10 

I tried array.max, but it just returns the maximum value7

+4
source share
4 answers

, array = [a, b, c], a, b c, , . , .

, , , , . :

hash = { a: 4, b: 7, c: 1}
+6

Ruby , , . array.max, Fixnum 7, .

Array . , , :

array[array.index(array.max)] = array.max + 10
#=> 17

array
#=> [4, 17, 1]

, Array, array.index(array.max) .

, , Array Ruby , Array , , , .


, , , .

+4

, - :

array.max + 10  # or any other manipulation for that matter.

, , Ruby Binding .

a = 4
b = 7
c = 1

array = [a, b, c]

# Select variable whose value matches with maximum of three elements
# Variable name as symbol is obtained by this process
var = binding.send(:local_variables).select do |i| 
    array.max.eql? binding.local_variable_get(i)
end.first
#=> :b

# Update value of variable using symbol representing  its name
binding.local_variable_set(var, binding.local_variable_get(var) + 10)

puts b
#=> 17

Binding # eval , :

binding.eval("#{var.to_s} += 10")
#=> 17

, var.to_s, var , , , eval.

+1

Array # index .

1.9.3-p484 :008 > max_elem = array.index(array.max)
 => 1
1.9.3-p484 :009 > array[max_elem] = array[max_elem] + 10
 => 11
1.9.3-p484 :010 > array
 => [4, 17, 1]
1.9.3-p484 :011 >
-1

Source: https://habr.com/ru/post/1621192/


All Articles