2

If I try to convert single String to date it works.

    require 'date'

    a=String.new
    a='20171023'
    puts b=Date.strptime(a,'%Y%m%d')
    puts b.yday()

How can I make it work with an array? I tried this way.

    require 'date'

    a=[20160106, 20132018, 20011221]
    b=a.each{|a| Date.strptime(a, '%Y%m%d').yday()}
    puts b
5
  • 2
    You should be using an Array of Strings, not Integers Commented Mar 30, 2018 at 19:07
  • 1
    What date would 20132018 parse to? Commented Mar 30, 2018 at 19:11
  • tried with a.map{|a| a.to_s} but it doesn't help Commented Mar 30, 2018 at 19:13
  • sorry 20132018 is just a example, can be any date Commented Mar 30, 2018 at 19:15
  • you tried same variable a withing block, try different one @lezi Commented Mar 30, 2018 at 19:17

2 Answers 2

3

You need to pass a string, instead an integer as you're doing now:

a = ['20160106', '20130218', '20011221']

If you want to store the result of each operation in b, then you can use map instead each:

b = a.map { |date| Date.strptime(date, '%Y%m%d') }

Your second date is invalid, I guess is 20130218.

require 'date'

a = %w[20160106 20130218 20011221]
b = a.map { |date| Date.strptime(date, '%Y%m%d').yday }
p b # [6, 49, 355]

%w[ ... ] is an array of strings, where you avoid using quotes and commas.

When you don't need to pass arguments to a method call, you can avoid parenthesis.

Sign up to request clarification or add additional context in comments.

Comments

1
require 'date'

a = [20160106, 20131018, 20011221]
a.map { |n| (Date.parse n.to_s).yday }

NB the array is different from the OP's, I assume he made a typo of some sort as the second number-date was invalid.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.