← Back to Ruby Course | Chapter 3: Strings | Lesson 4 of 7

String Formatting कैसे करें

String formatting एक template को एक set style में values से भरता है, stamped blanks वाले एक form letter की तरह। आप जो दिखता है इसके decimals और width control कर सकते हैं।

In this page:

  1. String Formatting
Syntax
ruby
format("%s is %d years old", string_value, integer_value)
"%.2f" % decimal_value

String Formatting

% operator (या format/sprintf methods) %s, %d, और %.2f जैसे format specifiers इस्तेमाल करते हुए एक string में values format करता है, C के printf जैसा।

यह plain interpolation से output पर ज़्यादा precise control देता है, जैसे fixed decimal places या zero-padding। format और sprintf same underlying behavior के लिए aliases हैं।

Note: format("%.2f", value) एक number को exactly 2 decimal places तक format करने का standard तरीका है।

उदाहरण: String Formatting

markup
name = "Alice"
score = 92.567

puts format("Name: %s, Score: %.2f", name, score)
puts "Padded: %05d" % 42
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक decimal value के साथ %d इस्तेमाल करना और rounding की उम्मीद करना, जब यह truncate करता है।
  2. कई specifiers के साथ % को एक array की बजाय एक single argument pass करना, जैसे "%s %s" % "a", जो ArgumentError raise करता है।
  3. एक literal percent sign के लिए %% भूल जाना।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.