Ruby/Language Basics/puts
Материал из Wiki.crossplatform.ru
(Различия между версиями)
Версия 17:10, 26 мая 2010
Array on righthand side for multiple args
puts "%s: %f" % ["pi", Math::PI]
Comparing Floating-Point Numbers
puts 1.8 + 0.1 # => 1.9 puts 1.8 + 0.1 == 1.9 # => false puts 1.8 + 0.1 > 1.9 # => true
%d for decimal integers
puts "%d" % 10 # => "10": %d for decimal integers
Display a Message
puts "Hello from Ruby."
exponential with uppercase E
puts "%E" % 1234.567 # => "1.234567e+03": exponential with uppercase E
Field and precision combined
puts "%6.4g" % 123.456 # " 123.5": four significant digits in field six chars wide puts "%3s" % "ruby" # "ruby": string argument exceeds field width puts "%3.3s" % "ruby" # "rub": precision forces truncation of string
Field width
puts "%5s" % "<<<" # " <<<": right-justify in field five characters wide puts "%-5s" % ">>>" # ">>> ": left-justify in field five characters wide puts "%5d" % 123 # " 123": field is five characters wide puts "%05d" % 123 # "00123": pad with zeros in field five characters wide
Float number Precision
puts "%.2f" % 123.456 # "123.46": two digits after decimal place puts "%.2e" % 123.456 # "1.23e+02": two digits after decimal = three significant digits puts "%.6e" % 123.456 # "1.234560e+02": note added zero puts "%.4g" % 123.456 # "123.5": four significant digits
force exponential notation
puts "%e" % 1234.567 # => "1.234567e+03": force exponential notation
format a string with puts
#!/usr/bin/env ruby puts "%s, %s!" % [ "Hello", "myValue" ]
format based string interpolation
#!/usr/bin/env ruby hi = "Hello, %s" puts hi % "myValue!" # => "Hello, myValue!" puts hi % "people!" # => "Hello, people!" puts hi % "universe!" # => "Hello, universe!"
full-length floating-point numbers
puts "%f" % 1234.567 # => "1234.567000": full-length floating-point numbers
Get the command line parameter
#!/usr/bin/env ruby puts "Hello, #{ARGV[0]}!"
hexadecimal integers
puts "%x" % 10 # => "a": hexadecimal integers
Insert some output from a shell command
puts "Hey Matz, I"m running " + "ruby --version"
Multiple arguments to be formatted
puts args = ["Syntax Error", "test.rb", 20] # An array of arguments "%s: in "%s" line %d" % args # => "Syntax Error: in "test.rb" line 20"
octal integers string format
puts "%o" % 10 # => "12": octal integers
Put two or more variables together with the + method:
hi = "Hello, " person = "Matz!" puts hi + person # => Hello, Matz!
Simple Arithmetic
puts 1.0 + 2.0 puts 2.0 * 3.0 puts 5.0 - 8.0 puts 9.0 / 2.0 # This is what the program returns: 3.0 6.0 -3.0 4.5
six significant digits
puts "%g" % 1234.567 # => "1234.57": six significant digits
uppercase hexadecimal integers
puts "%X" % 10 # => "A": uppercase hexadecimal integers
Use %f or %e depending on magnitude
puts "%g" % 1.23456E12 # => "1.23456e+12": Use %f or %e depending on magnitude
use parentheses
puts 5 * (12-8) + -15 puts 98 + (59872 / (13*8)) * -52