0

I have 1 field delivery_time It is in an array include :

DELIVERY_TIME = [
    I18n.t("activerecord.attributes.order.none_delivery_time"),
    "09:00~12:00",
    "12:00~14:00",
    "14:00~16:00",
    "16:00~18:00",
    "18:00~20:00",
    "19:00~21:00",
    "20:00~21:00",
  ].freeze

when I downloaded the csv directory it was in the form

"09:00~12:00"

but i want now when I download it will take the form :

"0912"

how to customize it?

my code:

def perform
    CSV.generate(headers: true) do |csv|
      csv << attributes
      orders.each do |order|
        csv << create_row(order)
    end
  end
end


def create_row(order)
    row << order.delivery_time
end
2
  • is delivery_time enum? or it's value must be one of the DELIVERY_TIME? don't understand why it's an array? Commented Apr 12, 2020 at 7:07
  • It is intended to display selections in the view, allowing the user to enter only these values Commented Apr 12, 2020 at 7:10

2 Answers 2

2

AFAIU, you need to modify DELIVERY_TIME to fit your format. CSV is absolutely out of scope here. So to transform values, one should split by and take the hour from the result.

DELIVERY_TIME = [
    "09:00~12:00",
    "12:00~14:00",
    "14:00~16:00",
    "16:00~18:00",
    "18:00~20:00",
    "19:00~21:00",
    "20:00~21:00",
].freeze

DELIVERY_TIME.map { |s| s.split('~').map { |s| s[0...2] }.join }
#⇒ ["0912", "1214", "1416", "1618", "1820", "1921", "2021"]

A safer method would be to use DateTime#parse for this

require 'time'
DELIVERY_TIME.map do |s|
  s.split('~').map { |s| DateTime.parse(s).strftime("%H") }.join
end
#⇒ ["0912", "1214", "1416", "1618", "1820", "1921", "2021"]

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

Comments

0

It's not real clear what you're asking, but I'd probably start with something like this:

"09:00~12:00".scan(/\d{2}/).values_at(0, 2).join # => "0912"

Using that in some code:


"09:00~12:00".scan(/\d{2}/).values_at(0, 2).join # => "0912"

DELIVERY_TIME = [
    'blah',
    "09:00~12:00",
    "12:00~14:00",
    "14:00~16:00",
    "16:00~18:00",
    "18:00~20:00",
    "19:00~21:00",
    "20:00~21:00",
  ].freeze

ary = [] << DELIVERY_TIME.first
ary += DELIVERY_TIME[1..-1].map { |i|
  i.scan(/\d{2}/).values_at(0, 2).join
}  
# => ["blah", "0912", "1214", "1416", "1618", "1820", "1921", "2021"]

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.