首页 > 解决方案 > 将散列表中弹出的类对象分配给变量?

问题描述

我有一个我制作的类类型的二维哈希表。我正在尝试从该哈希表中弹出一个值并将其分配给一个变量:

foo = @bar[0].pop()

但是,foo没有填充对象。我已经确保@bar[0].pop实际上弹出了正确的对象,因为我的原始实现是在带有以下代码的 Class 方法中:

@test.each {|x| return @bar[x].pop() if something == x }

并且该方法返回正确的对象。但是,我正在尝试在方法中执行更多操作,这需要我将弹出的对象保存在变量中,我不确定如何通过赋值来做到这一点,或者我的语法是否不正确。

编辑:这是我的实际代码(相关的东西)

class Candy
   attr_accessor :name, :shelved

   def initialize
      @name = ""
      @shelved = 0
   end
end

class Shelf
   attr_accessor :candy_hash, :total_candies, :shelf_full, :num_candies,
                  :name_array

   def initialize()
      @candy_hash = Hash.new{ |h, k| h[k] = []}
      @total_candies = 0
      @shelf_full = 0
      @name_array = Array.new
   end
end

class Shop
   attr_accessor :shelves, :unshelved_hash, :unshelved_names

   def initialize
      @shelves = []
      @unshelved_hash = Hash.new{ |h, k| h[k] = []}
      @unshelved_names = []
   end
   
   def push_new_unshelved(candy)
      @unshelved_names << candy.name
      @unshelved_hash[@unshelved_names.last].push(candy)
   end

   def push_existing_unshelved(candy)
      @unshelved_names.each{|x| @unshelved_hash[x].push(candy) && break if x == candy.name}
   end

   def receive_candy(candy)
      check = self.check_if_exists(candy)
      if check == 0
         self.push_new_unshelved(candy)
      else
         self.push_existing_unshelved(candy)
      end
   end

   def get_hash_key(candy_name)
      @unshelved_names.each{|x| return x if candy_name == x}
   end


   def get_unshelved_candy(candy_name)
      candy = @unshelved_hash[self.get_hash_key(candy_name)].pop()
      return candy 
      # problem is here, candy is never populated 
      # I'm gonna do more in this method but this is the important part
      # working solution right now: return @unshelved_hash[self.get_hash_key(candy_name)].pop()
   end

   def shelve_single(candy_name)
      candy = self.get_unshelved_candy(candy_name)
      @shelves[self.find_empty_shelf].add_candy(candy)
   end
end

shop1.receive_candy(Candy.new("snickers"))
shop1.shelve_single("snickers")


标签: ruby

解决方案


注意:此答案基于很多假设,以填补您问题中的空白。

如果要将值分配给方法中的变量,则需要使用break而不是。退出整个方法,同时仅中断当前迭代器(在您的情况下):returnreturnbreakeach

def my_method
  my_value = @test.each {|x| break @bar[x].pop() if something == x }
  ...
end

推荐阅读