Problem to select a specific object within a hash

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 , and category (this attribute also represents the hash key)).

Each instantiated object of this class is saved in an object called Floriculture which is an instance of the Floriculture class. In the floriculture 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 this, the user must enter the value assigned to the field 'code' of the flower object that will be deleted. The system must then search within the hash flowers, looking at each category and each object contained therein, one that has an integer value corresponding to that requested by the user. I'm having problems exactly in the function block responsible for finding this value and deleting it. follow 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 block select, I put flower.codigo! = code, it can assign the variable object, all the flowers even the one with the same value in the code field and then, clean everything from the hash! >
asked by anonymous 20.03.2017 / 15:02

1 answer

0

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

@floricultura.flores.each do |categoria, flores|
   flores.delete_if { |flor| flor.codigo == @codigo }
end
    
20.03.2017 / 15:31