ruby - 将散列表中弹出的类对象分配给变量?
问题描述
我有一个我制作的类类型的二维哈希表。我正在尝试从该哈希表中弹出一个值并将其分配给一个变量:
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")
解决方案
注意:此答案基于很多假设,以填补您问题中的空白。
如果要将值分配给方法中的变量,则需要使用break
而不是。退出整个方法,同时仅中断当前迭代器(在您的情况下):return
return
break
each
def my_method
my_value = @test.each {|x| break @bar[x].pop() if something == x }
...
end
推荐阅读
- python - 如何以 hh:mm:ss 格式将时间转储到 txt 文件
- scala - Scala 仅通过检查案例类的特定字段来添加要设置的元素
- java - 如何在 Java 中测试 Getter 和 Setter
- wso2 - 在 wso2 apim 中安装功能
- python - python - selenium 给出错误 geckodriver 需要在 PATH 中(即使它是)
- html - 在一个文件中多次使用 CSS 类
- kubernetes - Kubernetes 管理多个应用程序的 Pod 副本之间的流量
- jquery - Jquery:查找和替换文本
- ssh - “输入的 MAC 损坏。” 当从 VirtualBox/Ubuntu 在 VPN 上通过 SSH 进行 git 克隆时
- c++ - 为什么我用于在堆栈中打印最大元素的 C++ 代码没有产生正确的输出?