Ruby/Number/Convert to String

Материал из Wiki.crossplatform.ru

Версия от 17:59, 13 сентября 2010; ViGOur (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

constant value interpolation

number = 5
puts "The number is #{5}."                           # => "The number is 5."



Convert float to string

(256.0).to_s # => "256.0"



Convert integer to string by parameter

42.to_s(10)                       # => "42"
-100.to_s(2)                      # => "-1100100"
255.to_s(16)                      # => "ff"
1442151747.to_s(36)               # => "number"



Convert string to integer with error

"6".to_i(2)                       # => 0
"0".to_i(1)
# ArgumentError: illegal radix 1
40.to_s(37)
# ArgumentError: illegal radix 37



Integer passed into a string with interpolation

x = 2
print "This application is running okay if 2 + 2 = #{x + x}"



String interpolation with calculation

number = 5
puts "The number prior to #{number} is #{number-1}."



String interpolation with method call

number = 5
puts "The number after #{number} is #{number.next}."



Substituting Variables Into Strings

number = 5
"The number is #{number}."                      # => "The number is 5."