如何将附加数据设置为散列中的键
How to set the appended data as the key in a hash
我试图让日期成为我的哈希键,然后让余额的总和成为我的哈希数组中的值,以便稍后在返回将打印日期、金额和金额的账户报表时使用哈希余额。
代码如下:
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
如何让日期成为散列键?我目前正在尝试将其附加到数组中,但这只是添加到数组中。
据我了解,您想添加一些东西作为散列的键。
你可以用 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!
文档:
Adds the contents of other_hash to hsh. If no block is specified, entries with duplicate keys are overwritten with the values from other_hash, otherwise the value of each duplicate key is determined by calling the block with the key, its value in hsh and its value in other_hash.
我试图让日期成为我的哈希键,然后让余额的总和成为我的哈希数组中的值,以便稍后在返回将打印日期、金额和金额的账户报表时使用哈希余额。
代码如下:
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
如何让日期成为散列键?我目前正在尝试将其附加到数组中,但这只是添加到数组中。
据我了解,您想添加一些东西作为散列的键。
你可以用 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!
文档:
Adds the contents of other_hash to hsh. If no block is specified, entries with duplicate keys are overwritten with the values from other_hash, otherwise the value of each duplicate key is determined by calling the block with the key, its value in hsh and its value in other_hash.