溫馨提示×

Ruby怎么進(jìn)行字符串操作和格式化

小億
100
2024-04-11 12:04:03
欄目: 編程語言

Ruby中有許多內(nèi)置的方法用于字符串操作和格式化。下面是一些常用的方法:

  1. 字符串拼接和連接:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
puts result
  1. 字符串格式化:
name = "Alice"
age = 30
result = "#{name} is #{age} years old"
puts result
  1. 字符串大小寫轉(zhuǎn)換:
str = "hello world"
puts str.upcase   # 輸出大寫字符串
puts str.capitalize   # 輸出首字母大寫字符串
puts str.downcase   # 輸出小寫字符串
  1. 字符串截取和替換:
str = "hello world"
puts str[0..4]   # 輸出從第一個字符到第五個字符
puts str.gsub("world", "ruby")   # 將字符串中的"world"替換為"ruby"
  1. 字符串查找和分割:
str = "hello world"
puts str.include?("world")   # 判斷字符串中是否包含"world"
puts str.split(" ")   # 將字符串按空格分割成數(shù)組

這些只是Ruby中字符串操作和格式化的一些常用方法,還有許多其他方法可以進(jìn)行更復(fù)雜的操作。您可以查看Ruby官方文檔以獲取更多信息。

0