0

I'm trying to get the date to be my hash's key and then have the total of the balance be the value in my hash array to use the hash later when returning an account statement which will print date, amount and balance.

Here is the code:

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

How would I get the date to be the hash key? I'm currently trying to append it in but that's just adding to the array.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
JBDR
  • 55
  • 4

1 Answers1

0

As I understand it, you want to add something as a key to the hash.

You can do it with merge!, something like this:

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")

Here's the merge! documentation from the Ruby section on APIdock:

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
GosuGod
  • 300
  • 1
  • 8
  • 1
    There's no point in using `merge!` or `merge` if the hash is empty. If `dt` is your `DateTime` object (e.g, `dt = DateTime.now`), it's easier to just write `hash = { dt=>value }`, `hash ={ dt.to_s=>value }` or `hash = { dt.to_s.to_sym=>value}`, depending on requirements. – Cary Swoveland Feb 24 '20 at 18:22
  • Thanks for the advice! But what if hash will not be empty? He will use merge method. Based on this merge method can be used for empty and not empty hash :) – GosuGod Feb 25 '20 at 07:01
  • If the hash `hash` is not empty you can use `merge`, but it's simpler to just write `hash[dt.to_s] = value`. The disadvantage of using `merge` here is that there are two steps: create the single-key hash that will be merged, then perform the merge. `merge` is mainly used when you are combining two existing hashes or wish to add multiple key-value pairs to a hash. – Cary Swoveland Feb 25 '20 at 08:10
  • Understood! Thanks for the advice again! – GosuGod Feb 25 '20 at 08:24