vendredi 19 novembre 2021

Ruby get variable in another method (undefined local variable or method )

The function is to display the correct final price for each number. For example, if there are 5 bottles, it should get results for: 5 * 2 + 10 = 15

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { apple: 1, bottle: 2, headphone: 3, wallet: 5 }

The function to get value is like this :

def find_value(key)
  val = AaaBbb.numbers[key] # this will be nil if the key isn't found
  val || 0
end

The function to calculate the money is (HAS ERROR HERE, NEED TO UPDATE):

  def calculate
      quantity * find_value + 10
  end

Now it has an error:

undefined local variable or method `val' for #AaaBbb:0x00007f7cd9443240 Did you mean? eval Extracted source (around line #33):

   def calculate
     quantity * val + 10
   end

Question:

How to solve the problem by modifying the find_value or calculate functions? If you have any better ideas, please feel free to share.

Aucun commentaire:

Enregistrer un commentaire