首页 > 代码库 > Ruby_day[1]输入(gets)和输出(puts, print)

Ruby_day[1]输入(gets)和输出(puts, print)

question:

  1: chomp是?

  2: first_name.capitalize!后面的感叹号有什么作用?

  3: #{first_name}

 1 print "What‘s your first name?" 2 first_name = gets.chomp 3 first_name.capitalize! 4  5 print "What‘s your last name?" 6 last_name = gets.chomp 7 last_name.capitalize! 8  9 print "What city are you from?"10 city = gets.chomp11 city.capitalize!12 13 print "What state or province are you from?"14 state = gets.chomp15 state.upcase!16 17 puts "Your name is #{first_name} #{last_name} and you‘re from #{city}, #{state}!"18 
run->Whats your first name? jyWhats your last name? pwnWhat city are you from? shenzhenWhat state or province are you from? guangdongYour name is Jy Pwn and youre from Shenzhen, GUANGDONG!nil

gets是ruby中的方法,用来获取用户的输入。当得到输入后,Ruby会在输入的数据后面自动添加一个空行(新的一行)。

chomp是用来移除这个新添加的行,也就是得到输入后,不会自动添加空行。

 

1 print "This is my question?" 2 answer = gets.chomp #输入 bad3 answer2 = answer.capitalize  #-> Bad, answer还是bad4 answer.capitalize! #现在answer是Bad
  answer -> Bad

!的作用是直接改变answer的值无需再创建一个变量来记录。

 

1 first_name = "Kevin"2 puts "Your name is #{first_name}!"3 4 #将会输出 Your name is Kevin!5 #kevin取代了#{first_name} 相当于一个字符串的格式

 

Ruby_day[1]输入(gets)和输出(puts, print)