Ruby學習筆記一_ruby專題

來源:互聯網
上載者:User

筆記:

Ruby會預設返回方法中的最後一個值。
如果需要返回多個值,可以用數組來實現。
可以通過強制聲明return來傳回值。
基礎的輸出方法是用puts(輸出一行),print(直接列印)。
基礎的輸入方法是gets(讀入一行,包含行尾的'\n',可以用chomp方法消除)。
純粹的現象對象語言,而且還是一個動態語言(雖然今天目前還沒用到),所以老老實實物件導向去。
有兩種簡單粗暴的儲存多個元素的方法。數組[]和雜湊表{},而且還有各種各樣的函數。
強烈推薦新手入門線上學習網站: http://tryruby.org/ ,簡直爽到爆!
各種代碼

eg1: 建立一個雜湊表

ojs = {}ojs["poj"] = :Aojs["hdu"] = :Aojs["uva"] = :Bojs["zoj"] = :Bojs["CF"] = :Sojs["TC"] = :Sratings = Hash.new(0)ojs.values.each { |rate| ratings[rate] += 1 } print ratings puts "" puts "===============================" print ojs puts "" puts "===============================" 3.times {print "hey!"} puts "" puts "==============================="  print ojs.length puts "" print ojs.keys puts "" print ojs.values puts "" ojs.keys.each { |name| print name; print " "; print ojs[name]; puts ""; } puts "===============================" print File.read("x.txt") puts "===============================" File.open("x.txt", "a") do |f|   f << "HACKED!\n"   end print File.read("x.txt") puts "===============================" print File.mtime("x.txt") puts "" print File.mtime("x.txt").hour puts "" puts "==============================="

eg2: 從檔案讀資料建立一個雜湊表

# 讀取一個檔案的資料庫並且輸出def load_oj( path ) ojs = {}  File.foreach(path) do |line|  name, value = line.split(':')  ojs[name] = value end print_oj(ojs)enddef print_oj( data ) puts "================================" print "name\tvalue\n" data.keys.each do |name|  puts "#{name}\t#{data[name]}" end puts "================================"endoj = load_oj("x.txt")


eg3: 從檔案中讀取學生資訊並且輸出

# 從檔案中讀取學生資訊並且輸出class Student#attr_accessor :name#attr_accessor :numberdef initialize(name = "Unknown", number = "2012309999")@name = name@number = numberenddef printputs "#{@name}\t#{@number}"endenddef load_stu( path )data = {}File.foreach(path) do |line|na, no = line.split(' ')s = Student.new(no, na)data[s] = 1enddataenddef print_stu( data )puts "================================"print "name\tnumber\n"data.keys.each do |stu|stu.printendputs "================================"enddata = load_stu("y.txt")print_stu(data)

eg4: 一行內輸入4個整數,計算這四個數的最大公約數

# 一行內輸入4個整數,計算這四個數的最大公約數def gcd(a, b) if b === 0  return a else return gcd(b, a % b) endendstr = gets.chompa, b, c, d = str.split(" ")g1 = gcd(a.to_i, b.to_i);g2 = gcd(c.to_i, d.to_i);g3 = gcd(g1, g2)puts "gcd(#{a}, #{b}, #{c}, #{d}) = #{g3}"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.