从零开始学 Ruby 之四: 字符串类


#1

字符串类

上节课由 @fsckzy 自告奋勇代课,鼓掌,这节继续由 04 哥哥讲.接着说处理字符串的那些方法.

更多的创建方式

str1 = "现在时间是 #{Time.now} "
str2 = 'Hello Siri'
str3 = %Q{Polly said: "Ming Niu Said: "I love boys!""}
str4 = %q/Snail said: "OK,I got it."/
str5 = %!"Are you normal?""Of course not."!
str6 = <<"EOF"
Deserializes JSON string by converting year <tt>y</tt>, month <tt>m</tt>,
day <tt>d</tt>, hour <tt>H</tt>, minute <tt>M</tt>, second <tt>S</tt>,
offset <tt>of</tt> and Day of Calendar Reform <tt>sg</tt> to DateTime.
EOF
str7 = `echo 04`

仔细体会下其中的差别和适用场景.

更多的常用方法

p 'Hei' + 'Halo'  # => "HeiHalo"
p 'OOXX' * 3   # => "OOXXOOXXOOXX"
p '我是我' == '我是我' # => true
p 'who'.upcase  # => "WHO"
p 'ruby'.size  # => 4
p str2[0]  # => "H"
p str2[1]  # => "e"
p str2[0,3]  # => "Hel"
p str2[0..-1]  # => "Hello Siri"
p 'ABC'.reverse # => "CBA"

感觉有点吃力?也许你并不熟悉计算机专业英语,找个翻译软件试试看?

练习题:

str8 = 'go!'
str9 = 'Let us GO!'
str = str8 [_1_] + str9 [_2_]
p str  # => 'Go!Go!Let us GO!'

请问 [1] 和 [2] 中应该填入什么以便让代码成立?

答案不唯一,可以开放脑洞.

更多的文档可以参考这里.


#2

前面两条好理解。
这几条理解不了,完全看不懂

str3 = %Q{Polly said: “Ming Niu Said: “I love boys!””}
str4 = %q/Snail said: “OK,I got it.”/
str5 = %!“Are you normal?”“Of course not.”!

常用方法包含了以下知识
upcase 是小写转换为大写的函数
size 是计算有几个字符的
reverse 是颠倒顺序的。数字也可使用

ruby中字符串是从0开始计算的。

irb(main):027:0> str2 = ‘Hello Siri’
=> "Hello Siri"
irb(main):028:0> str2[0] # => “H”
=> “H”

作业那里,为什么会有两个go,而且还变成了大写?

irb(main):039:0> str = str8[0…-1] + str9[0…-1]
=> "go!Let us GO!"
irb(main):040:0> str = str8[0…-1] * 2 + str9[0…-1]
=> “go!go!Let us GO!”


#3
%Q => 用双引号创建字符串
%q => 用单引号创建字符串
% => 省略 Q 创建字符串,同双引号

Ruby 中的字符串下标是从零开始计算的.

作业的那个答案不对,仔细观察题目.从零取到负一相当于调用了原有的整个字符串,填到此处意义不明.


#4

str = str8.capitalize * 2 + str9.chomp

str = str8.capitalize + str9.insert(0,‘Go!’)

str = str8.capitalize(6,‘Go!’) + str9[0…-1]

str = str8.tr(‘g’,‘G’) * 2 + str9[0…-1]

str = str8.capitalize.concat(str8.capitalize) + str9[0…-1]

str = str8[2,0] + str9[7,3] *2 + str9[0…-1]

str = str8.capitalize *2 + str9.byteslice(0,10)

str = str8.capitalize*2 << ‘Let us Go!’ + str9[9,0]

str = str8.capitalize*2 << ‘Let us Go!’ + str9.clear


#5

勤劳的小蜜蜂.
拼接,变换,裁剪,很多脑洞方式.


#6

厉害了。原来是这个意思。