七週七語言自習——Ruby第一天

Ruby第一天,介紹了一些Ruby的基本語法,並點出了面向對象的一個重要思想:對接口編程,不對實現編程。只要有相同接口,咱們不用關注其內部實現,能夠進行相同的調用。編程

a = ['100', 100.0]
i = 0
while i < 2
  puts a[i].to_i
  i = i + 1
end

>>100
>>100

上面的代碼中,'100'和100.0是不一樣的類型,但他們有相同的方法to_i,就能夠進行相同的調用。小程序


練習ruby

1.打印字符串"Hello world."。spa

上手新語言怎麼能少得了它?code

puts 'Hello world.'


2.在字符串"Hello, Ruby."中,找出"Ruby."的下標。對象

直接調用字符串的index方法接口

puts 'Hello, Ruby.'.index('Ruby.')

3.打印你的名字十遍。字符串

調用Fixnum的times方法get

10.times{puts 'Z'}

4.打印字符串"This is sentence number 1.",其中的數字1會一直變化到10。input

最基本的循環

i = 1
while i <= 10
  puts "This is sentence number #{i}."
  i = i + 1
end

5.寫一個選隨機數的程序。讓玩家猜隨機數是多少,並告訴玩家是猜大了仍是猜小了。

很簡單的小程序:

puts 'Guess the number! 0~9'
var = rand(10)
inputNum = 10
while var != inputNum
  input = gets()
  inputNum = input.to_i
  if inputNum > var
    puts 'Bigger!' 
  elsif inputNum < var
    puts 'Smaller!'
  end
end
puts 'Bingo!'
相關文章
相關標籤/搜索