红宝石 |字符串插入方法
insert是 Ruby 中的 String 类方法,用于在给定索引处的字符之前插入指定的字符串,修改给定的字符串。负索引从字符串末尾开始计数,并插入到给定字符之后。
Syntax: str.insert(index, other_str)
Parameters: Here, str is the given string.
Returns: A modified string.
示例 1:
# Ruby program to demonstrate
# the insert method
# Taking a string and
# using the method
puts "Ruby".insert(0, 'Z')
puts "Program".insert(3, 'Z')
输出:
ZRuby
ProZgram
示例 2:
# Ruby program to demonstrate
# the insert method
# Taking a string and
# using the method
puts "Sample".insert(-4, 'Z')
puts "Articles".insert(-5, 'Z')
输出:
SamZple
ArtiZcles