Problem to select a specific object within a hash

Asked

Viewed 108 times

2

Hello! Good morning. I have the following situation: In my Ruby code, there is a flower class(attributes: code(generated by a function with auto increment), name, value and category(this at ributo also represents the key of the hash)).

Each instantiated object of this class is saved in an object called Floriculture which is an instance of the Floriculture class. In the flower shop class, we have the following code::

class Floricultura
  attr_accessor :flores
  def initialize
    @flores = {}
  end

  def adiciona(flor)
    @flores[flor.categoria] ||= []
    @flores[flor.categoria] << flor
  end

  def floresArray
    @flores.values.flatten
  end

Where @flores represents the hash that will store each flower object, separating them by category.

In the main code, there is a menu and among the options offered, there is the option to delete a flower. To do so, the user must enter the value assigned to the 'code' field of the flower object that will be deleted. The system must then search within the flower hash, looking in each category and in each object contained in it, one that has integer value corresponding to that requested by the user. I’m having trouble exactly in the function block responsible for finding this value and erasing it. follows the code:

  def opttres
    puts "Digite o código da flor que irá ser apagada: "
    @codigo = gets.chomp
    @floricultura.flores.each do |categoria, flores|
        objeto = flores.select{|flor| flor.codigo == @codigo}
        puts categoria
        puts flores
        puts objeto
        @floricultura.flores[categoria].delete(objeto)
        puts "flor #{objeto} deletada"
    end
  end
end

some information:

  • def opttres represents the third menu option
  • if, at the end of the select block, I put flower.code != code, it can assign the variable object, all flowers even the one with the same value in the code field and then, clean everything from the hash!

1 answer

0

You do not need to select in the array and then delete, you can do everything together with the method delete_if array:

@floricultura.flores.each do |categoria, flores|
   flores.delete_if { |flor| flor.codigo == @codigo }
end
  • Whoa, man! blz? So before I saw your answer, I was able to solve my problem! I could have done in this way that you mentioned but as I wanted to return the name of the selected object to print on the screen "Flower x was deleted", I thought of incorporating this object to a variable (in this case, the var object). My solution was very simple: "@code = gets.chomp.to_i" converted to integer the value passed by the user and so the system was able to compare this value with you in the code attribute of each flower, which is an integer!

  • @Mikhaelaraujo No problem man. The important thing is that it worked! =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.