Ruby中的字符串操作和格式化输出可以使用内置的字符串方法和格式化指令来实现。
在Ruby中,可以使用双引号或单引号来定义一个字符串。例如:
str1 = "Hello, world!"
str2 = 'Hello, Ruby!'
在Ruby中,可以使用+
运算符来拼接两个字符串。例如:
str1 = "Hello, "
str2 = "world!"
str3 = str1 + str2
puts str3 # 输出 "Hello, world!"
也可以使用<<
方法来直接将字符串添加到另一个字符串的末尾。例如:
str1 = "Hello, "
str2 = "world!"
str1 << str2
puts str1 # 输出 "Hello, world!"
在Ruby中,可以使用sub
和gsub
方法来进行字符串的替换操作。其中,sub
方法只替换第一个匹配到的字符串,而gsub
方法会替换所有匹配到的字符串。例如:
str = "Hello, world!"
new_str = str.sub("world", "Ruby")
puts new_str # 输出 "Hello, Ruby!"
str = "Hello, world! Hello, Ruby!"
new_str = str.gsub("Hello", "Hi")
puts new_str # 输出 "Hi, world! Hi, Ruby!"
在Ruby中,可以使用split
方法来将一个字符串分割成多个子字符串。例如:
str = "Hello,world, Ruby"
arr = str.split(",")
puts arr.inspect # 输出 ["Hello", "world", " Ruby"]
在Ruby中,可以使用upcase
和downcase
方法分别将字符串转换为大写和小写。例如:
str = "Hello, world!"
new_str1 = str.upcase
new_str2 = str.downcase
puts new_str1 # 输出 "HELLO, WORLD!"
puts new_str2 # 输出 "hello, world!"
在Ruby中,可以使用printf
方法进行格式化输出。其中,printf
方法的第一个参数是格式化字符串,后面的参数是要输出的变量。格式化字符串由普通字符和格式控制字符组成。
%s
:代表字符串类型。%d
:代表整数类型。%f
:代表浮点数类型。%e
:以科学计数法形式输出浮点数类型。%x
:以十六进制形式输出整数类型。以下是一些常见的格式化字符串示例:
name = "Ruby"
age = 26
height = 170.5
# 字符串类型
printf("My name is %s\n", name)
# 整数类型
printf("I am %d years old\n", age)
# 浮点数类型
printf("My height is %.2f\n", height) # 保留两位小数
# 科学计数法形式的浮点数类型
printf("My height is %.2e\n", height)
# 十六进制形式的整数类型
printf("My age in hex is %x\n", age)
以上代码的输出结果为:
My name is Ruby
I am 26 years old
My height is 170.50
My height is 1.71e+02
My age in hex is 1a