Updating new value of a variable

a = 10
b = 20
c = a+b # i will get result here 30
after these step i will give a = 20
and puts c => expected result is 40 (i dont want to reapeat again c = a+b)
how can i do this

You will have to repeat your addition: each line you write is executed in turn, and so ‘c’ is given the value 30 when you set it - the formula is not recorded. When you change ‘a’ you only affect ‘a’. If you want to change the value of ‘c’ to reflect the new value of ‘a’, you will need a new line to set ‘c’.

(You may be thinking of how a spreadsheet works, where changing a value in one cell will affect the value in another cell which refers to the first. That is not how Ruby works.)

is there any logic to get the result?

Like @pcl has noted, you need to force the c = a + b to be re-evaluated after you update the contents of a. You can use a lambda to achieve this effect, but in this case it is of limited value.

a = 10
b = 20

c = lambda {a + b}

puts c.call

a = 20

puts c.call
1 Like

whatever you did here can i do for the below values
a = 1
str = “my value is:#{a}”
a = 2 # updating a value
puts str # result is: my value is:1
but my expected result should get like below
puts str #result is: my value is:2

No, you cannot update a variable ‘automatically’ in that way. Your ‘expectation’ is not in keeping with how Ruby works (or any other imperative programming language, for that matter).

If you want to keep ‘relationships’ between data values, you can use a class.


class Values
  def set_a value
    @a = value

  def set_b value
    @b = value

  def get_c # this uses the latest values of 'a' and 'b'
    return @a + @b

So you would use it like:

v = Values.new
v.set_a 1
v.set_b 2
puts "C's value is #{v.get_c}" # => shows 3
v.set_a 2
puts "C's value is #{v.get_c}" # => shows 4

okay thank you so much for clarifying my problem

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

| Privacy Policy | Terms of Service | Remote Ruby Jobs