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
b += 10
I tried array.max, but it just returns the maximum value7
array.max
7
, array = [a, b, c], a, b c, , . , .
array = [a, b, c]
a
c
, , , , . :
hash = { a: 4, b: 7, c: 1}
Ruby , , . array.max, Fixnum 7, .
Fixnum
Array . , , :
Array
array[array.index(array.max)] = array.max + 10 #=> 17 array #=> [4, 17, 1]
, Array, array.index(array.max) .
array.index(array.max)
, , Array Ruby , Array , , , .
, , , .
, - :
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.
var.to_s
var
eval
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 >
Source: https://habr.com/ru/post/1621192/More articles:Onchange events for multiple text fields - javascriptHow to send a file to Nodejs using FormData and send Node a confirmation message? - javascriptwhat does + = operation really do on a scala card? - scalaReading / writing Windows registry on 64-bit Win 7 using JAVA with JNA - javaHow to listen for angular 2 MANUALLY events on a nested dependency instance? - angularCMake will not link the C library to a C ++ program - c ++DropDown functional menu using only CSS and HTML? - htmlhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1621195/annotationjava-config-based-application-starts-to-look-for-xml-config-file-when-moved-from-weblogic12c1213-to-weblogic12cr2-1221&usg=ALkJrhjYykI8oEgOKiEp5cVemI-JTHnIhwcentering responsive sections with images inside - htmlHow to put text after input field in python? - pythonAll Articles