Reputation: 1399
I have a time-stamp '2016-02-08 16:23:53'
and an array containing different time-stamps ['2016-02-09 14:23:53', '2015-02-08 16:23:53', '2016-02-08 16:22:53']
.
What is the simplest way to check if the value is less than any of the value in array and return true
or false
?
Upvotes: 2
Views: 170
Reputation: 1864
Checking if a value is less than any value in an array may be accomplished in Ruby with
value < array_of_values.min
The simplest way to solve the example given by the OP is
'2016-02-08 16:23:53' < ['2016-02-09 14:23:53',
'2015-02-08 16:23:53',
'2016-02-08 16:22:53'].min
Comparing string representations of dates and times will only work if all strings involved use the same format, the numbers are ordered from big to small (years down to seconds), and the numbers use leading zeros.
The use of adequate data types (like Time or DateTime) instead of strings for storing and processing dates and times will improve the robustness of the software.
Upvotes: 5
Reputation: 121000
If timestamps are strings:
['2016-02-09 14:23:53', '2015-02-08 16:23:53', '2016-02-08 16:22:53'].none? do |ts|
Time.parse(ts) > Time.parse('2016-02-08 16:23:53')
end
If timestamps are already instances of Time
, there is no need for parse
:
timestamps_array.none? do |ts|
ts > Time.parse('2016-02-08 16:23:53')
end
Well, for the sake of @sawa’s patience :)
It is inefficient to parse the value to compare against each time in the loop:
timestamp_to_check = Time.parse('2016-02-08 16:23:53')
['2016-02-09 14:23:53', '2015-02-08 16:23:53', '2016-02-08 16:22:53'].none? do |ts|
Time.parse(ts) > timestamp_to_check
end
Upvotes: 6