柚子快報(bào)激活碼778899分享:Ruby字符串
柚子快報(bào)激活碼778899分享:Ruby字符串
在 Ruby 中,字符串使用雙引號(hào)或單引號(hào)括起來(lái)的一連串字符表示,可以使用一系列字符串操作方法來(lái)進(jìn)行處理。
創(chuàng)建字符串:
str1 = "hello"
str2 = 'world'
puts str1 # hello
puts str2 # world
Ruby 中的字符串也支持多行字符串,可以使用 `<<-` 或 `%Q{}` 來(lái)表示:
str3 = <<-STR
This is a
multi-line
string.
STR
str4 = %Q{
Another
multi-line
string.
}
puts str3
puts str4
字符串操作方法:
1. 連接字符串:
?? 使用 `+` 或 `<<` 運(yùn)算符可以將兩個(gè)或多個(gè)字符串連接起來(lái):
str1 = "hello"
str2 = "world"
puts str1 + " " + str2 # hello world
puts str1 << " " << str2 # hello world
2. 格式化字符串:
?? 使用 `%` 運(yùn)算符可以將變量插入字符串中:??
name = "John"
age = 24
puts "My name is %s. I am %d years old." % [name, age]
# My name is John. I am 24 years old.
3. 查找子串:
?? 使用 `include?` 方法可以查找字符串中是否包含某個(gè)子串:
str = "hello world"
puts str.include?("world") # true
puts str.include?("ruby") # false
4. 替換子串:
?? 使用 `gsub` 方法可以將字符串中的某個(gè)子串替換為另一個(gè)字符串:
str = "hello world"
new_str = str.gsub("world", "ruby")
puts new_str # hello ruby
5. 截取子串:
?? 使用 `slice` 或 `[]` 方法可?```ruby以截取字符串的一部分:
str = "hello world"
puts str.slice(0, 5) # hello
puts str[6..10] # world
6. 其他常用方法:`upcase`(全部大寫(xiě))、`downcase`(全部小寫(xiě))、`capitalize`(首字母大寫(xiě))、`reverse`(反轉(zhuǎn)字符串)、`strip`(刪除字符串兩側(cè)的空格)等。
柚子快報(bào)激活碼778899分享:Ruby字符串
精彩內(nèi)容
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。