vendredi 19 novembre 2021

Ruby on rails: function to find value by key

I just encountered a problem with ruby syntax:

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { a: 1, b: 2, c: 3, d: 5 }

or

class AaaBbb < ApplicationRecord

 enum number: { "a" => 1, "b" => 2, "c" => 3, "d" => 5 }

The function is:

  def find_value
    AaaBbb.numbers.each do |key, value|
        puts "#{key} = #{value}"
      if key == AaaBbb.numbers[:key] (WRONG CODE HERE, NEED TO FIX)
        return value
      else
        return 0
      end
    end
  end

So I am trying to write a function that if it finds the key, then return the value. For example that if I find look up some product(key), it will return the correct price(value) to display.

Thanks, and feel free to share if you have any better way to solve it.

Aucun commentaire:

Enregistrer un commentaire