Ruel Nopal
Ruel Nopal

Reputation: 415

How to change "string" to date month or year in ruby

How to convert a string like this

    "6.months" => 6.months
    "6.years" => 6.years

I know how to split these characters but I don't know how to make the string as an object of the date class.

Thanks

Upvotes: 0

Views: 455

Answers (2)

iGian
iGian

Reputation: 11193

Maybe something like this?

require "active_support/core_ext/integer/time"

'6.months'.split('.').then{ |n, t| n.to_i.public_send t }

#=> 6 months

So:

Date.today + '6.months'.split('.').then{ |n, t| n.to_i.public_send t }

Or patching the String class:

module MyStringPatch
  def to_integer_time
    self.split('.').then{ |n, t| n.to_i.public_send t }
  end
end

String include MyStringPatch

Date.today + '6.months'.to_integer_time

Or if you trust the evil eval (see comments), you can also just do:

Date.today + eval('6.months')

By the way, as pointed by @AlekseiMatiushkin

If it comes from the user input, #public_send might also be dangerous

Upvotes: 4

David Seeherr
David Seeherr

Reputation: 131

If you are completely sure you have a valid object of ActiveSupport::Duration, you can do something like the following:

amount, time_span = '6.months'.split('.')
duration = amount.to_i.public_send(time_span)

Date.today + duration

amount is the String 6 and time_span is the String months. duration is the ActiveSupport::Duration 6 months. The result will be the present day in 6 month, which is a Date

Upvotes: 2

Related Questions