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?
[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
.
© 2024 OneMinuteCode. All rights reserved.