How to create a date object from a hash in ruby

Asked 2 years ago, Updated 2 years ago, 43 views

date_hash={
  :year=>2015,
  —month=>12,
  :day=>15,
}

I would like to create a date object by doing something like Date.new(date_hash).
Would you like to play it like Ruby?

ruby

2022-09-30 14:25

1 Answers

[19]pry(main)>Date.new(*date_hash.values)
=>#<Date: 2015-12-15(2457372j, 0s, 0n), +0s, 2299161j)>

Is it like this?

values is the basic instance method of hash.
It will appear as soon as you search, so please check it yourself.
ruby hash values-Google Search

* is less searchable, so I quote it.
Method call (with super block, field) (Ruby 2.2.0)

If the last argument is preceded by a *, the value of the argument is expanded and passed.Deployment is done via method to_a.I mean:

foo(1,*[2,3,4]) 
foo(1,*[])` 

are each

foo(1,2,3,4) 
foo(1) 

Same as

In other words,

[20]pry(main)>date_hash.values
=>[2015, 12, 15]

If you pass it as it is, you will get an error.

[24]pry(main)>Date.new([2015, 12, 15])
NoMethodError: undefined method `<' for [2015, 12, 15]: Array
from(pry): 28: in `new'

It means that it is developed and handed over.
The following two have the same meaning.

[25]pry(main)>Date.new(*[2015, 12, 15])
[26]pry(main)>Date.new(2015, 12, 15)

You may want to search by ruby split.

As tmtms pointed out, values_at will be more robust.
You may want to check the difference between values and values_at.


2022-09-30 14:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.