How to View rails Hours, Minutes, and Seconds

Asked 2 years ago, Updated 2 years ago, 36 views

I want to show 1 hour 2 minutes 3 seconds in → view if I have hour:1 minute:2 second:3 and data

The hour may be nil, so if the hour is nil, the time should not be displayed.
minute, second contains a value.

I can only think of a way to make conditional branching with if, but is there a way to make it implemented neatly with methods?

unless result.run_hour.nil?
    hour=result.run_hour.to_s+"time"
  else
    hour=""
  end

  unless result.run_minute.nil?
    minute=result.run_minute.to_s+"minute"
  else
    minute=""
  end

  unless result.run_second.nil?
    second=result.run_second.to_s+"seconds"
  else
    second=""
  end

  hour+minute+second

ruby-on-rails ruby

2022-09-30 11:19

2 Answers

I don't know if it's refreshing or not, but I don't know if it's like this.

[hour, minute, second].zip(["hour", "minute", "second"]).select(&:first).join


2022-09-30 11:19

You can write it like this.

"#{hour&.to_s&.+'time'}#{minute&.to_s&.+'minute'}#{second&.to_s&.+'second'}"


2022-09-30 11:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.