【问题标题】:How to set the appended data as the key in a hash如何将附加数据设置为哈希中的键
【发布时间】:2020-02-24 12:54:59
【问题描述】:

我试图让日期成为我的哈希键,然后让余额的总和成为我的哈希数组中的值,以便稍后在返回将打印日期、金额和余额的帐户对帐单时使用哈希。

代码如下:

class Bank
  attr_accessor :total, :time

  def initialize
    @total = 0
    @time = [:date => @total]
  end

  def deposit(sum)
     @total += sum
  end

  def withdrawl(sum)
    @total -= sum
  end

  def input_time
    @time << Time.now.strftime('%d/%-m/%Y')
  end

  def yesterday
    @time << Time.at(Time.now.to_i - 86400).strftime('%d/%-m/%Y')
   end
end

如何让日期成为哈希键?我目前正在尝试将其附加,但这只是添加到数组中。

【问题讨论】:

    标签: ruby ruby-hash


    【解决方案1】:

    据我了解,您想添加一些东西作为哈希的键。

    你可以用merge! 来做,像这样:

    require "time"
    time = DateTime.now.to_s
    hash = {}
    value = "value123"
    hash.merge!("#{time}": "#{value123}")
    p hash
    
    #=> {:"2020-02-24T18:36:40+04:00"=>"value123"}
    #merge!("KEY": "VALUE")
    

    这是来自 APIdock Ruby 部分的merge! 文档:

    other_hash 的内容添加到 hsh。如果未指定块,则具有重复键的条目将被 other_hash 中的值覆盖,否则每个重复键的值通过调用具有该键的块来确定,其值在 hsh 及其在 other_hash 中的值。

    【讨论】:

    • 如果哈希为空,则使用 merge!merge 毫无意义。如果 dt 是您的 DateTime 对象(例如,dt = DateTime.now),则根据要求编写 hash = { dt=&gt;value }hash ={ dt.to_s=&gt;value }hash = { dt.to_s.to_sym=&gt;value} 会更容易。
    • 感谢您的建议!但是如果 hash 不为空呢?他将使用合并方法。基于此合并方法可用于空和非空哈希:)
    • 如果哈希hash 不为空,您可以使用merge,但写hash[dt.to_s] = value 更简单。这里使用merge的缺点是有两个步骤:创建将被合并的单键哈希,然后执行合并。 merge 主要用于组合两个现有哈希或希望将多个键值对添加到哈希中。
    • 明白!再次感谢您的建议!
    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2021-07-22
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多