When you make a string…what does it mean to “format” that string?
CHALLENGE: Explain this to me like I’m an absolute idiot. Like, take it to a condescending level. Be mean about it. I’m talking how you would explain a lemonade stand to a very, very stupid child.
4
2 Answers
The most common use of the phrase refers to the replacing of variable placeholders within a string with the correct string representations of the variables’ contents.
Consider:
temp_reading = 25.67528
puts "It is currently %0.1f degrees" % [temp_reading]
-> It is currently 25.7 degrees
String formatting is what turns the template into the string you see in the output.
1
Appreciate it, Phil! Slowly putting the pieces together…
–
As pointed out by Phil Taprogge, typically formatting a string refers to changing the representation of data for presentation reasons.
Phil’s Example
long_number = 1.11111111111111111111111111111111111111111111111111111111111
puts "%0.1f" % long_number
=> 1.1
puts "%d" % long_number
=> 1
There is tons of documentation on string formatting and typically it can carry over to different languages since this come from the C programming language printf
.
Formatting a string could refer, however, to any and all transformations to a string for presentation.
str = "hello world"
str.downcase
=> "hello world"
str.upcase
=> "HELLO WORLD"
str.capitalize
=> "Hello world"
str.titlieze
=> "Hello World"
str.parameterize
=> "hello-world"
1
Thanks @fbelanger! This is super helpful. Just read both of your links — I’m learning in Ruby and am SO dumb at this juncture that I (embarrassingly) didn’t even realize this concept applied to other languages. Really appreciate the thorough explanation.
–
See also stackoverflow.com/a/39172098/421705
it’s really a broad, imprecise question, which is why it’s hard to explain as simply as you request. to ‘format a string’ could mean any number of things depending on the context. See http://www.blackbytes.info/2012/01/ruby-string-formatting/
Stack Overflow uses a Question and Answer format, meaning questions should address specific programming issues and answers should be succinct and precise. Perhaps you could do better by a) researching fundamentals using a search engine before asking here or; b) taking this back to reddit where /r/ruby would be more open to receiving imprecise discussions. Please take the time to review the Stack Overflow help file before asking further questions.
Copy that guys, thanks for the links. Read through them both and slowly putting the pieces together…