Similar to the Ruby on Rails page, this is a growing collection of snippets and notes for the Ruby programming language.
Something I came up with the other day while working on the console that someone might find useful. It’s a one-liner that can be used to display progress when processing data on the Ruby (or Rails) console. It makes use of the \033[F
escape sequence.
def progress(current, limit)
puts "\033[F #{((current/limit.to_f) * 100).round(3)}%"
end
The \033[F
is the escape code for "beginning of line above" or something like that. The output is overwritten each time the method is called, unless other output was displayed in between. Use it like this, for example:
objects.each_with_index do |object, idx|
# do something
progress(idx, objects.size)
end
It's astonishing how few developers are using benchmarks while producing code. In the last 10 years, I cannot remember working with a single developer who used benchmarks to evaluate their code's performance. What a shame! It is so easy too. Here's one quick way using Ruby's built-in Benchmark
class:
require 'benchmark'
Benchmark.bmbm do |x|
x.report("first") { some_method1('blabla') }
x.report("second") { some_method2('blabla') }
x.report("third") { some_method3('blabla') }
end
Here's a useful overview of Formats for Date and Time1 to be used with #strftime
.
@note.updated_at.strftime("%Y-%m-%d")
# => 2023-01-31
@note.updated_at.strftime("%B %d, %Y")
# => Jan 1, 2023