如何计算服务年限
how to compute year of service
我有这个问题
1 年服务 15 天
3 年服务 17 天
5 年服务 20 天
10 年或更长时间服务 25 天
所以想出这段代码,我得到了雇员的雇用年份
这是代码
def year_of_service(date_of_hired)
years = [1, 3, 5, 10]
now = Time.now.utc.to_date
get_year = now.year - date_of_hired.year - ((now.month > date_of_hired.month ||
(now.month == date_of_hired.month && now.day >= date_of_hired.day)) ? 0 : 1)
end
我的解决方案是我将使用 if 语句,但对我来说这将是一个很长的代码是否有其他解决方案可以缩短它或其他可能的解决方案
问题就在这里我怎么知道 'get_year' 是否在我的数组之间???
示例:
'get_year' 是 4 怎么知道是 3 年的服务不是 5 但 4 不在数组中
您可以雇用 take_while
或 select
。
y = [1, 3, 5, 10]
y.take_while { |i| i <= 4 }.max #=> 3
y.select { |i| i <= 4 }.last #=> 3
但是这些涉及收集比需要更多的元素。另一种方法是找到符合条件的最后一个元素的索引,然后使用正则 array-notation 来获取该元素:
y[y.rindex { |i| i <= 4 }] #=> 3
您也可以使用 find
,但这需要先反转数组。目前 Ruby 中没有 rfind
。
我有这个问题
1 年服务 15 天
3 年服务 17 天
5 年服务 20 天
10 年或更长时间服务 25 天
所以想出这段代码,我得到了雇员的雇用年份
这是代码
def year_of_service(date_of_hired)
years = [1, 3, 5, 10]
now = Time.now.utc.to_date
get_year = now.year - date_of_hired.year - ((now.month > date_of_hired.month ||
(now.month == date_of_hired.month && now.day >= date_of_hired.day)) ? 0 : 1)
end
我的解决方案是我将使用 if 语句,但对我来说这将是一个很长的代码是否有其他解决方案可以缩短它或其他可能的解决方案
问题就在这里我怎么知道 'get_year' 是否在我的数组之间???
示例:
'get_year' 是 4 怎么知道是 3 年的服务不是 5 但 4 不在数组中
您可以雇用 take_while
或 select
。
y = [1, 3, 5, 10]
y.take_while { |i| i <= 4 }.max #=> 3
y.select { |i| i <= 4 }.last #=> 3
但是这些涉及收集比需要更多的元素。另一种方法是找到符合条件的最后一个元素的索引,然后使用正则 array-notation 来获取该元素:
y[y.rindex { |i| i <= 4 }] #=> 3
您也可以使用 find
,但这需要先反转数组。目前 Ruby 中没有 rfind
。