'%02d' % 2
When you want to write the number 2 as '02' in ruby, you write a syntax like '% 02d'% 2
.
The method is to pad the argument with 0 and return it as a string, but what exactly is%, 02, or d here?
In ruby, the notation% has various meanings.
Example: 5% 3 => 2
Example:"% 02d "% 2 =>" 02 "
Example:% w (dog cat monkey) => ["dog", "cat", "monkey"]
Example:% x [DATE] =>" Wednesday, June 24, 2020 09:31:57 JST \ n "
There are the above types. Reference: Meanings of symbols used in Ruby (excluding complex symbols in regular expressions)
The syntax '% 02d'% 2
shown above is equivalent to the 2. String class "%" operator
in the above example!
d is one of the ** "indicators" ** that indicate the type of the argument. d represents a decimal number (Decimal number). Other directives include those that represent strings, those that represent floating point numbers, and those that represent exponential notation.
02 can be decomposed into 0 and 2, indicating ** "flag" ** and ** "width" **, respectively. There are several types of ** "flags" **, but 0 means to fill the margins with 0s. ** "Width" ** is left as it is, and the length at the time of output is specified.
To summarize these, the notation '% 02d'% 2
is
'% 0 (Please fill the margin with 0 ~) 2 (The length at the time of output is 2) d (Represent the argument as a decimal integer'% (% operator of String class Yo ~) 2 (The argument is 2!)
It means that it has the meaning.
Arguments can also be passed as an array, so
** When you say "I want to convert a decimal color code to a hexadecimal color code" **
You can write '% 02x% 02x% 02x'% [255, 255, 255] =>" ffffff "
!
Recommended Posts