第一个 Ruby 程序
学习如何创建并运行第一个 Ruby 程序。
Hello World
现在是时候用 Ruby 编写我们的第一个程序了,这个程序将简单地在屏幕上显示消息 “Hello World!”。
这是我们用来编写 Ruby 代码的代码编辑器。通过点击编辑器底部的“运行”按钮,就可以执行我们的 Ruby 程序:
1print "Hello World!" # 输出 Hello World!
注意: 我们可以在 Ruby 程序中添加非执行文本,只需在文本开头加上井号 (
#)。这种文本称为 注释。我们使用注释来在程序中添加说明。
下面的程序与上面的程序相同,输出结果也一致。唯一的区别是,我们在下面的程序中为 print 语句添加了括号。使用 () 不会影响代码的输出结果,但能让代码更易读。
1print("Hello World!") # 使用括号输出 Hello World!
在输出中添加换行
我们可以通过在 print() 语句中使用 "\n" 将一句话拆分为多行。字符串 "\n" 在 print 语句中会引入一个新行。为了更好地理解,可以向 AI 导师寻求帮助。
1print("Single") 2print("Line\n") 3print("Separate New Line\n")
自定义消息并使用变量
在下面的程序中,我们将一个字符串存储在变量 name 中,并使用 #{} 内的 print() 语句输出它。我们可以使用 #{} 在 print() 语句中输出变量。#{} 运算符会在字符串中进行表达式替换,但它本身不会出现在输出结果中。
注意: 变量名只能包含字母(A–Z 和 a–z)和下划线符号(_)。也可以包含数字(0–9),但变量名不能以数字开头。例如,
Key_2是合法的变量名,而2_key不是。变量名区分大小写,这意味着name、Name和NAME是三个不同的变量。
1name = "Educative" 2print("Hello User. Welcome to #{name}")
在 Ruby 中,我们使用 gets 来获取输入(从用户读取值)。
让我们编写另一个 Ruby 程序,先获取用户的姓名,再显示问候信息。我们使用 name 作为变量来存储用户输入的内容。
左侧代码编辑器中的 main.rb 是程序文件的名称。.rb 表示这是一个 Ruby 程序。首先,我们使用 print() 语句输出提示文字 "Enter your name: ",然后使用 gets 获取输入。当我们运行这个程序时,会弹出一个黑色的屏幕,称为终端,在这里我们可以输入数据并查看输出结果:
No configuration found for ID: 9ef6917c3d6604afdf1b2193e9acbf306784b2057b8ce084db88f4bc3da0606b
输出末尾的单词 exit 表示程序在终端中已执行完毕。
上述代码在第一行显示消息 "Hello",接着显示 name 变量的值。第二行则显示 "Welcome to Educative"。
在上方的代码编辑器中,如果我们仅使用 gets 获取输入,它会在 print 语句中导致换行。我们可以使用 gets.chomp 来避免换行。
No configuration found for ID: f834611b50ee55a14ef6d21b14250554c997b22a743f918295d73e603695e013
上述代码将输出内容显示在同一行。
Ruby 编程练习
让我们练习编写第一个 Ruby 程序,该程序能从用户那里获取多个输入。请记住以下建议:
编写更清晰代码的小贴士:
- 可以为
()。- 使用
"\n"可以在代码中添加换行。- 可以使用
#{}在print()中输出变量。- 可以使用
gets.chomp避免换行。
讲一个故事
让我们编写一个程序,根据用户提供的信息讲一个故事。程序应要求用户输入姓名、年龄、城市、大学、职业以及宠物的名字。
同时请注意,代码中输入的顺序必须与要求一致。程序应按如下格式显示故事,并将用户输入的内容插入到相应位置:
1There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted an animal named PETNAME. They both lived happily ever after!
No configuration found for ID: e6a044866cc6b8b5899a8e87fba14c47098802f6e255653abcf8122ba9df74de
你可以在上方的代码编辑器中运行以下代码:
1print("Enter user's name: ") 2userName = gets.chomp 3print("Enter user's age: ") 4userAge = gets.chomp 5print("Enter user's city: ") 6userCity = gets.chomp 7print("Enter user's college: ") 8userCollege = gets.chomp 9print("Enter user's profession: ") 10userProfession = gets.chomp 11print("Enter user's pet name: ") 12userPet = gets.chomp 13 14print "\nThere once was a person named #{userName} who lived in #{userCity}. At the age of #{userAge}, #{userName} went to college at #{userCollege}. #{userName} graduated and went to work as a #{userProfession}. Then, #{userName} adopted an animal named #{userPet}. They both lived happily ever after!\n"