【问题标题】:How to push keys and values into an empty hash w/ Ruby?如何使用 Ruby 将键和值推送到空哈希中?
【发布时间】:2013-02-22 22:27:11
【问题描述】:

我有一个字典类,并希望能够使用“添加”方法将键(作为关键字)和值(作为定义)推送到空哈希中。我不明白如何在语法上编写它。我也包含了一个 RSPEC 文件。

红宝石:

 class Dictionary
     attr_accessor :keyword, :definition
     def entries
          @hash = {}
     end
     def add(options)
          options.map do |keyword, definition|
               @hash[keyword.to_sym] = definition
          end
     end
 end

Rspec:

 require 'dictionary'

   describe Dictionary do
   before do
       @d = Dictionary.new
   end
   it 'can add whole entries with keyword and definition' do
       @d.add('fish' => 'aquatic animal')
       @d.entries.should == {'fish' => 'aquatic animal'}
       @d.keywords.should == ['fish']
   end

感谢任何帮助。谢谢!

更新: 谢谢戴夫牛顿的回复。我使用了你的代码并得到了这个错误:

错误:

 *Failure/Error: @d.keywords.should == ['fish']
 NoMethodError:
 undefined method `keywords' for #<Dictionary:0x007fb0c31bd458 
 @hash={"fish"=>"aquatic animal"}>*

当我使用 @hash[word.to_sym] = defintion 将 'word' 转换为符号时出现不同的错误

 *Failure/Error: @d.entries.should == {'fish' => 'aquatic animal'}
   expected: {"fish"=>"aquatic animal"}
        got: {:fish=>"aquatic animal"} (using ==)
   Diff:
   @@ -1,2 +1,2 @@
   -"fish" => "aquatic animal"
   +:fish => "aquatic animal"*

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    Dictionaryinitialize 中实例化您的哈希:

    class Dictionary
      def initialize
        @hash = {}
      end
    
      def add(defs)
        defs.each do |word, definition|
          @hash[word] = definition
        end
      end
    end
    

    现在你没有哈希,直到你调用entries,你没有。

    entries 应该返回 现有散列,而不是创建一个新散列。

    keywords 应该返回哈希的键。

    您不需要keyworddefinition 的访问器。这样的单数项在字典类中是没有意义的。您可能想要像lookup(word) 这样返回定义的东西。

    此外,您将单词转换为符号,但我不知道为什么——特别是因为您在规范中使用了字符串键。选择一个,虽然我不相信这是符号增加价值的情况。

    请仔细考虑变量命名以提供尽可能多的上下文。

    【讨论】:

      【解决方案2】:

      查看您的 Rspec,您似乎需要此设置。

      class Dictionary
        def initialize
          @hash = {}
        end
      
        def add(key_value)
          key_value.each do |key, value|
            @hash[key] = value
          end
        end
      
        def entries
           @hash
        end
      
        def keywords
           @hash.keys
        end
      
      end
      

      不要在add方法中使用key.to_sym,只需要key

      为了给添加方法提供灵活性,我可以返回self对象继续添加。

      def add(key_value)
        key_value.each do |key, value|
          @hash[key] = value
        end
        self
      end
      

      所以,我现在可以这样做了。

      @d.add("a" => "apple").add("b" => "bat")
      

      【讨论】:

        猜你喜欢
        • 2017-01-04
        • 1970-01-01
        • 2016-05-16
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 2019-11-21
        • 1970-01-01
        相关资源
        最近更新 更多