编程打卡:来玩玩Ruby语言吧!

发布时间 2023-04-24 17:28:11作者: satou_matsuzaka

编程打卡:来玩玩Ruby语言吧!

打印字符串"Hello, World."

puts('Hello, World')
Hello, World
=> nil

在字符串"Hello, Ruby."中,找到"Ruby."的所在下标

'Hello, Ruby.'.index('Ruby')
=> 7

打印你的名字十遍

for i in 1..10
    puts('你的名字')
end
你的名字
你的名字
你的名字
你的名字
你的名字
你的名字
你的名字
你的名字
你的名字
你的名字
=> 1..10

打印字符串 "This is sentence number 1.",其中的数字 1 会一直变化到 10 。

for i in 1..10
    puts("This is sentence number #{i}.")
end
This is sentence number 1.
This is sentence number 2.
This is sentence number 3.
This is sentence number 4.
This is sentence number 5.
This is sentence number 6.
This is sentence number 7.
This is sentence number 8.
This is sentence number 9.
This is sentence number 10.
=> 1..10

从文件运行Ruby程序

在合适的目录创建一个 .rb 结尾的文件,里面写上程序的内容,然后终端中使用 ruby 文件名 这样的命令执行即可。

猜随机数小游戏

targetNumber = rand(10)
puts "Guess a number between 0 and 9"
guess = gets().to_i
until guess == targetNumber do
    if guess > targetNumber
        puts('too big')
    elsif guess < targetNumber
        puts('too small')
    end
    guess = gets().to_i
end
puts('Congratulation')

运行结果

Guess a number between 0 and 9
6
too big
3
too big
2
Congratulation