[Ruby] What is the percentage of’%02d’ %2?

1 minute read

#’%02d’ %2

When you want to write the number 2 as ‘02’ in ruby, you write syntax like '%02d' %2. It is a method to fill the argument with 0 and return it as a string, but what is this %, 02 or d?

% What?

In ruby, the notation% has various meanings.

  1. Remainder “%” Example: 5 %3 => 2
  2. ”%” operator of String class Example: "%02d" %2 => "02"
  3. Literal notation “%” operator Example: %w(dog cat monkey) => ["dog", "cat", "monkey"]
  4. Command line input Example: %x[ DATE ]=> "Wednesday 24th June 2020 09:31:57 JST\n"

There are types as described above. Reference: Meaning of symbols used in Ruby (excluding complex symbols in regular expressions)

The syntax '%02d' %2 shown above is equivalent to 2. String class "%" operator in the above example!

What is ## 02 or d?

d is one of the “directives” ** that indicates the argument type. d represents a decimal integer. Other directives include strings, floats, and exponents.

02 can be decomposed into 0 and 2, indicating “flag” and “width” respectively. There are several kinds of “flags” **, but 0 means that the margin is filled with 0. Specify the length at the time of output while leaving ** “Width” as it is.

Putting these together, the notation '%02d' %2 is

'%0 (Please fill in the blanks with 0~) 2 (The length at the time of output is 2.) d (Please represent the argument as a decimal integer.'% (% operator of the String class. Yo~) 2 (the argument is 2!)

It means that the meaning is put.

in conclusion

Arguments can be passed as an array, so ** When I say “I want to convert the color code expressed in decimal number to the hexadecimal color code” ** You can write '%02x%02x%02x' %[255, 255, 255] => "ffffff"!