Ruby中的字符串处理非常灵活

"abc"[0]  返回97 就是a
"abc"[1] 98
"abc"[2] 99
"abc"[3] nil
"abc"[-1] 99 从后向前数
"abc"[-2] 98
"abc"[-3] 97
"abc"[-4] nil


"abc" * 2 返回"abcabc" 支持乘法运算

"abc" + "def"  返回"abcdef"

"abcdef"[0,1]  "a"  从位置0开始抽取1位
"abcdef"[1,3] "bcd"
"abcdef"[-3,3] "def"
"abcdef"[1..3] "bc"  从1到3

来一个猜谜语的程序

Ruby之旅(十) Ruby中的字符串words = ["hallo","world","lee"]
Ruby之旅(十) Ruby中的字符串puts 
"guess word by \"#{words.join(",")}\""
Ruby之旅(十) Ruby中的字符串
scret = words[rand(3)]
Ruby之旅(十) Ruby中的字符串
while guess = gets
Ruby之旅(十) Ruby中的字符串  guess.chop!
Ruby之旅(十) Ruby中的字符串  
if guess == scret
Ruby之旅(十) Ruby中的字符串    puts 
"you win"
Ruby之旅(十) Ruby中的字符串    
break
Ruby之旅(十) Ruby中的字符串  
else
Ruby之旅(十) Ruby中的字符串    puts 
"you loss,guess?"
Ruby之旅(十) Ruby中的字符串  end
Ruby之旅(十) Ruby中的字符串end
Ruby之旅(十) Ruby中的字符串puts 
"the words is #{scret}"
Ruby之旅(十) Ruby中的字符串


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-27
  • 2022-02-24
  • 2021-06-14
  • 2022-02-18
猜你喜欢
  • 2022-12-23
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2021-10-27
  • 2021-12-10
  • 2021-11-05
相关资源
相似解决方案