简体   繁体   English

尝试迭代红宝石哈希时出现意外标签

[英]Unexpected label while trying to iterate over a ruby hash

I am in the process of trying to iterate over a ruby hash. 我正在尝试遍历红宝石哈希。 I'll have to admit that my knowledge of ruby is very poor and i am in the process of trying to correct that, and so please bear with me if this is a very elementary question. 我必须承认,我对红宝石的知识非常差,并且我正在尝试纠正这一问题,因此,如果这是一个非常基本的问题,请与我一起接受。

I am wondering if the syntax of my hash is off. 我想知道我的哈希语法是否关闭。 The reason why it is looking the way that it is is because it is part of a rakefile, and i need to incorporate multiple addresses in this. 它之所以如此,是因为它是rakefile的一部分,我需要在其中合并多个地址。 (which i've never done, i've always only had 1 address to worry about) I know the solution to this is to build the addresses in as a rakefile, and then loop over them. (我从未做过,我总是只需要担心1个地址)我知道解决方案是将地址作为rakefile生成,然后遍历它们。

clinic.build_address.each do | address, value |
                            {
                              (city: "Minneapolis"
                              state: "MN"
                              address1: "316 10th ave"
                              zip: "55414"),
                              (city: "Hudson"
                              state: "WI"
                              address1: "119 Belmont Street"
                              zip: "54016")
                            }
puts build_address

With what I have right now I am getting an unexpected label (it is not liking that I have 'city:minneapolis') 有了我现在拥有的东西,我得到了一个意外的标签(我不喜欢我拥有“ city:minneapolis”)

Would anybody be able to take a quick look at what I have with this? 有人可以快速浏览一下我的功能吗?

If your Clinic model has an Address model related, and you run build_address , you won't end up with a hash, but an ActiveRecord object. 如果您的 Clinic模型具有相关的 Address模型,并且您运行 build_address ,则不会以哈希表结尾,而是以ActiveRecord对象结尾。 However, I'm not sure what exactly your goal is. 但是,我不确定您的目标到底是什么。

To iterate a hash, you would use: 要迭代哈希,可以使用:

 
 
 
  
  some_hash.each do |key, value| # some logic using key and/or value end
 
  

Maybe you mean you want something like this: 也许您的意思是您想要这样的东西:

 addresses = [ { city: "Minneapolis" state: "MN" address1: "316 10th ave" zip: "55414" }, { city: "Hudson" state: "WI" address1: "119 Belmont Street" zip: "54016" } ] addresses.each { |a| clinic.build_address a } 

It's hard to understand what you are trying to do but your code is not a valid Ruby code. 很难理解您要做什么,但是您的代码不是有效的Ruby代码。 The closest I could get to is this: 我能找到的最接近的是:

{a: "b"}.each do | address, value |
  [
    {
      city: "Minneapolis",
      state: "MN",
      address1: "316 10th ave",
      zip: "55414"
    },
    {
      city: "Hudson",
      state: "WI",
      address1: "119 Belmont Street",
      zip: "54016"
    }
  ]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM