types_of_people = 10
x = "There are #{types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = "Those who know #{binary} and those who #{do_not}."
puts x
puts y
puts "抄课文10次" * 10
w = "This is the left side of..."
e = "a string with a right side."
puts w + e
除了#{},我们还可以使用%{}在字符串中插入变量,然后使用%来进行格式化
formatter = "%{first} %{second} %{third} %{fourth}"
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}
puts formatter % {
first: "I had this thing.",
second: "That you could type up right.",
third: "But it didn't sing.",
fourth: "So I said goodnight."
}
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: #{days}"
puts "Here are the months: #{months}"
puts """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
\ (反斜杆) 后紧跟一个字符,用来代表输出一些不容易表示的字符,比如\n代表新起一行(new line character),在引号包含的字符串里面可以用\+引号输出一个引号:
"I am 6'2\" tall." # escape double-quote inside string
'I am 6\'2" tall.' # escape single-quote inside string
还有\t(tab), \\ (输出\)等等
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat
程序员所有的工作都是在解决输入输出问题,之前我们学了很多输出(puts/print),接下来看看输入
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
print "Give me a number: "
number = gets.chomp.to_i
bigger = number * 100
puts "A bigger number is #{bigger}."
print "Give me another number: "
another = gets.chomp
number = another.to_i
smaller = number / 100
puts "A smaller number is #{smaller}."
除了通过gets来获取输入以外,我们还可以在命令行里面执行ruby ex13.rb这样的命令时,在后面加上更多的字符串作为输入,这称为ARGV(argument variable)
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
user_name = ARGV.first
prompt = '> '
puts "Hi #{user_name}."
puts "I'd like to ask you a few questions."
puts "Do you like me #{user_name}? ", prompt
likes = $stdin.gets.chomp
puts "Where do you live #{user_name}? ", prompt
lives = $stdin.gets.chomp
puts "What kind of computer do you have? ", prompt
computer = $stdin.gets.chomp
puts """
Alright, so you said #{likes} about liking me.
You live in #{lives}. Not sure where that is.
And you have a #{computer} computer. Nice.
"""