字体:  

ruby的文字列的部分总结

diyuxinlang 发表于: 2008-11-09 12:44 来源: Ruby Community

今天将ruby的文字列做了部分的总结.发到论坛里来,一是希望能方便大家,希望更多的人能喜欢上ruby.
二,也是希望能得到大家的补充与修正.

# 单行文字列的输出
Example: str = ‘hello the world’
p str    #=> “hello the world”
puts str    #=> hello the world

# 多行文字列的输出
Example: str = <<EOS
This is test.
Ruby, the Object Oriented Script Language.
EOS
puts str
#=>This is test.
Ruby, the Object Oriented Script Language.

# 文字列的结合
Example: str = ‘hello’
puts str + ‘ the world’    #=> hello the world

# 文字列的追加
Example: str = ‘hello’
str <<  ‘ the world’
puts str    #=> hello the world

# 生成重复的文字列
Example: str = ‘hello ‘
puts str*3    #=> hello hello hello

# 大小写字母的变换
Example: str = ‘I Love Ruby’
puts str.upcase    #=> I LOVE RUBY
puts str.downcase    #=> i love ruby

# 文字列中的部分文字的取得
Example: str = “Apple Banana Orange”
puts str[0..4]     #=> Apple
puts str[6, 6]     #=> Banana

# 文字列中的部分文字的置换
Example: str = “Apple Banana Apple Orange”
str[0..4] = “Vine”     #=> str = “Vine Banana Apple Orane”
str[5, 6] = “Lemon”     #=> str = “Vine Lemon Apple Orange”
str.sub(”Apple”, “Pine”)     #=> str = “Pine Banana Apple Orange”
str.gsub(”Apple”, “Pine”)     #=> str = “Pine Banana Pine Orange”

# 文字列中变数的展开
Example: value = 123
puts “value is #{value}”     #=> value is 123

# 文字列中方法的展开
Example:
def sub(str)
  “Hello, #{str}.”
end
puts “Say  #{sub(”Tomoya”)}”     #=> Say Hello, Tomoya.

# 削除文字列头和尾的空格
Example: str = ‘   Hello, Ruby!   ‘
p s.strip     #=> “Hello, Ruby!”

# 削除文字列尾部的换行
Example: str = ‘Hello, Ruby!\n’
p str.chomp    #=> “Hello, Ruby!”
p str.strip    #=> “Hello, Ruby!”

# 文字型向数值型的转换
Example: str = ‘99′
i = 1
puts i + str.to_i    #=> 100

# 数值型向文字型的转换
Example: str = ‘99′
i = 1
p i.to_s + str   #=> “199″

# 文字型(数值型)向浮点小数型的转换
Example: str = ‘99′
puts str.to_f    #=> 99.0

# 下一个文字列的取得
Example:
p “9″.succ     #>= “10″
p “a”.succ     #>= “b”
p “AAA”.succ     #>= “AAB”
p “A99″.succ     #>= “B00″
p “A099″.succ    #>= “A100″

# 检查文字列中是否有相同文字出现
Example: str = “Apple Banana Apple Orange”
puts str.index(”Apple”) #=> 0
puts str.index(”Banana”) #=> 6
puts str.index(”Apple”, 6) #=> 13

puts str.rindex(”Apple”) #=> 13
puts str.rindex(”Apple”, 6) #>= 0

# 文字列的居中,居左和居右
Example: str = “Ruby”
p str.center(10)     #=> “   Ruby   ”
p str.ljust(10)    #=> “Ruby      ”
p str.rjust(10)    #=> “      Ruby”

我的博客是:http://www.everyone-4649.com/.