Ruby Strings(字符串)

Ruby Strings(字符串)

我们知道,字符串是用于表示某些文本的字符序列。它们可能还包含一些数字,空格和符号。例如,“芒果”和“有3个芒果!” 都是字符串。通常,出于识别目的,字符串用引号引起来。

让我们了解一下,Ruby中的字符串是什么意思

字符串在Ruby中被视为对象。编程时会经常使用字符串。您将通过在界面上以消息形式显示消息来使用它们与用户进行通信。

弦形成

在Ruby中,可以使用单引号''或双引号“”形成字符串。据您一致,这两种情况都是相同的。您将在字符串插值期间发现差异。可以通过以下方式创建字符串:

    'I love Nhooo'
    #or
    "I love the tutorials of Nhooo"

通过字符串进行通信:

您可以通过以下方式在print和puts语句的帮助下打印字符串

# 使用打印语句:
print "Hello there!"
print "Welcome to Nhooo."
print "Go through the tutorials of your choice!"

# 使用puts语句:
puts # 仅打印新行
puts "Hello there!"
puts "Welcome to Nhooo."
puts "Go through the tutorials of your choice!"

输出结果

Hello there!Welcome to Nhooo.Go through the tutorials of your choice!
Hello there! 
Welcome to Nhooo.
Go through the tutorials of your choice!

您可能会注意到,使用puts语句时,字符串将以不同的行打印,但print语句并非如此。

字符串容器

我们经常需要将字符串存储在某个空间或内存中,为此我们使用了变量。可以使用赋值运算符=和单引号''或双引号“”通过以下方式将字符串存储在变量中:

# 将字符串分配给变量
variable_string = 'Hi there!'

# 打印字串 
puts variable_string

输出结果

Hi there!

它提高了代码的可重用性,因为我们不必多次键入相同的字符串,只需在需要字符串时调用变量即可。

字符串串联

串联只是意味着将两个字符串连接在一起。可以通过以下方式使用+运算符来连接两个或两个以上的字符串:

# 连接两个字符串
result_1 = "Include"+"help"

# 在变量中分配两个字符串
string_1 = "Hello"
string_2 = "World!"

# 字符串变量之间用空格隔开 
result_2 = string_1 + " " + string_2

# 打印值/字符串(即结果)
puts result_1
puts result_2

输出结果

Nhooo
Hello World!

现在让我们检查是否可以在以下代码的帮助下将整数变量与字符串变量连接起来:

示例

# 串 
string1="Roll no: "
# 整数 
roll=27

# 将结果连接并分配给f_str
# 它将返回错误
f_str=string1+roll

# 打印结果 
puts f_str

输出结果

main.rb:7:in '+': can't convert Fixnum into String (TypeError)
        from main.rb:7:in '<main>'

编译器将反映一个错误,因为不会将fixNum隐式转换为string。通过应用可以实现该目标to_s()

# 串 
string1="Roll no: "
# 整数 
roll=27

# 将结果连接并分配给f_str
#使用将fixNum转换为字符串。to_s()方法
f_str=string1+roll.to_s

# 打印结果 
puts f_str

输出结果

Roll no: 27

.to_s方法将任何数据类型的变量转换为字符串类型。

字符串插值

串联使输出难以调试且非常复杂。字符串插值法通过在#和花括号{}的帮助下以以下方式将变量嵌入字符串中,从而提供了一种实现此目的的简便方法:

# 将字符串分配给变量
str1 = "Hi there!"
str2 = "nhooo.com"

# 打印变量的值 
puts "#{str1} This is #{str2}"

输出结果

Hi there! This is nhooo.com

还可以使用String Interpolation实现将变量隐式转换为字符串,请考虑给定的示例

# 分配字符串和整数值 
# 到变量
str1 = "Hi there!"
marks = 89

# 使用字符串插值的隐式类型转换
puts "#{str1} You got #{marks} marks"

输出结果

Hi there! You got 89 marks

您会注意到,这里我们不必放置任何.to_s方法来进行转换。