简体   繁体   English

将PHP转换为Ruby(On Rails)

[英]Convert PHP to Ruby (On Rails)

    $fromDateTS = strtotime($start_date);
    $toDateTS = strtotime($end_date);

    for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24)) 
    {
        $currentDateStr = date("Y-m-d",$currentDateTS);
    }

How would I convert this php to ruby. 我怎么把这个PHP转换为ruby。 There doesn't seem to be a for loop in ruby that is similar to php 在ruby中似乎没有类似于php的for循环

There are many solutions for this. 有很多解决方案。 You can do this for instance: 你可以这样做:

from_start_date_ts = Time.parse(start_date)
to_date_ts = Time.parse(end_date)
current_date_ts = from_start_date_ts
while current_date_ts < to_date_ts
  current_date_ts += 1.day
  current_date_str = current_date_ts.strftime("%D")
end

I haven't tested it so it might not work as it is but it is more to show you one possible syntax for a loop in Ruby. 我没有对它进行测试,因此可能无法正常工作,但更多的是向您展示Ruby中循环的一种可能语法。 Note that you can use while in different ways: 请注意,您可以以不同方式使用while:

while [condition]
 # do something
end


begin
 # do something
end while [condition]

You can also use the loop syntax: 您还可以使用循环语法:

loop do
  # do something
  break if [condition]
end

Or the until loop: 或者直到循环:

until current_date_ts > to_date_ts
  current_date_ts += 1.day
  current_date_str = current_date_ts.strftime("%D")
end

There are more :) 还有更多:)

I would code it this way: 我会这样编码:

from_start_date_ts = start_date.to_date
to_date_ts = end_date.to_date
from_start_date_ts.step(to_date_ts, 1.day).to_a.map{ |step_date| current_date_str = step_date.to_s }

This gives you back an array of step_date strings. 这会返回一个step_date字符串数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM