Matthew Berman
Matthew Berman

Reputation: 8631

How do I remove elements in an array based on a date in ruby

I have an array like so:

[{"day"=>"2014-04-08", "v"=>3},
 {"day"=>"2014-04-09", "v"=>49},
 {"day"=>"2014-04-10", "v"=>4},
 {"day"=>"2014-04-11", "v"=>1587},
 {"day"=>"2014-04-12", "v"=>20},

How do I remove all elements from this array where the "day" is after '2014-04-10' for example (leaving only 4/11 and 4/12)

Upvotes: 0

Views: 240

Answers (2)

tyamagu2
tyamagu2

Reputation: 969

use Array#select or Array#reject and compare "day" using Date class.

require 'date'

[
  {"day"=>"2014-04-08", "v"=>3},
  {"day"=>"2014-04-09", "v"=>49},
  {"day"=>"2014-04-10", "v"=>4},
  {"day"=>"2014-04-11", "v"=>1587},
  {"day"=>"2014-04-12", "v"=>20}
].select { |d| Date.parse(d["day"]) > Date.new(2014, 4, 10) }

Upvotes: 1

August
August

Reputation: 12558

timestamp = Time.parse('2014-04-10')
arr = [...]

arr.keep_if { |h| Time.parse(h['day']) > timestamp }
# => [{"day"=>"2014-04-11", "v"=>1587}, {"day"=>"2014-04-12", "v"=>20}]

Upvotes: 1

Related Questions