Ruby编程之字符串赋值和字符串索引
【摘要】 笔者用Rubymine编写了字符串赋值和字符串索引小例子,供大家参考
s = "hello world"
print( "1) s='#{s}' and s.object_id=#{s.object_id}\n" )
s = s + "!" # this creates a new string object
print( "2) s='#{s}' and s.object_id=#{s.object_id}\n" )
s = s.capitalize # this creates a new string object
print( "3) s='#{s}' and s.object_id=#{s.object_id}\n" )
s.capitalize! # but this modifies the original string object
print( "4) s='#{s}' and s.object_id=#{s.object_id}\n" )
s[1] = 'A' # this also modifies the original string object
print( "5) s='#{s}' and s.object_id=#{s.object_id}\n" )
1) s='hello world' and s.object_id=60
2) s='hello world!' and s.object_id=80
3) s='Hello world!' and s.object_id=100
4) s='Hello world!' and s.object_id=100
5) s='HAllo world!' and s.object_id=100
s = "Hello world"
puts( s[1] ) #=> Ruby 1.8 displays 101; Ruby 1.9 displays 'e'
s = "Hello world"
puts( s[1,1] ) # prints out 'e'
e
e
puts( s[1].ord)
101
s = "Hello world"
puts( s[1] )
achar=s[1]
puts( achar )
puts( s[1,1] )
puts( achar.ord )
e
e
e
101
puts( s[1,3] )
ell
puts( s[1..3] ) # also prints 'ell'
puts( s[-1,1] ) # prints 'd'
puts( s[-5,5] ) # prints 'world'
puts( s[-5..5] ) # this prints an empty string!
puts( s[-5..-1] ) # prints 'world'
puts(s.length) #=> 11
puts(s.reverse!) #=> Hello world
puts(s.reverse) #=> dlrow olleH
puts(s.upcase)#=> HELLO WORLD
puts(s.capitalize) #=> Hello world
puts(s.swapcase) #=> hELLO WORLD
puts(s.downcase) #=> hello world
puts(s.insert(7,"NOT ")) #=> hello wNOT orld
puts(s.squeeze)#=> helo wNOT orld
puts(s.split) #=> ["helo", "wNOT", "orld"]
ell
d
world
world
11
dlrow olleH
Hello world
DLROW OLLEH
Dlrow olleh
DLROW OLLEh
dlrow olleh
dlrow oNOT lleH
dlrow oNOT leH
dlrow
oNOT
lleH
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)