Ruby筆記

1.數組遍歷方法總結

array = (1..10).to_a
length = array.length 
    length.times do t 
    print "#{array[t]} " 
    end 
    puts "n"
length = array.length-1 
    for i in 0..length do 
    print "#{array[i]} " 
    end 
    puts "n"
for i in array do 
        print "#{i} " 
    end 
    puts "n"
array.each{x print x," "} 
    puts "n"
length = array.length 
    i = 0 
    while i< length do 
    print "#{array[i]} " 
    i = i+1 
    end 
    puts "n"
length = array.length 
    i = 0 
    until i==length do 
    print "#{array[i]} " 
    i += 1 
    end 
    puts "n"
array.each_index do i 
    print "#{array[i]} "

2.Ruby鏈接數據庫

  • mysql
require 'mysql'  
    begin  
        db = Mysql.init  
        db.options(Mysql::SET_CHARSET_NAME, 'utf8')  
        db = Mysql.real_connect("127.0.0.1", "root", "123456", "test", 3306)  
        db.query("SET NAMES utf8")
        db.query("drop table if exists tb_test")  
        db.query("create table tb_test (id int,
        text LONGTEXT) ENGINE=MyISAM DEFAULT CHARSET=utf8")  
        db.query("insert into tb_test (id, text) values ( 
        1,'first line'),(2,'second line')")  
        printf "%d rows were inserted\n",db.affected_rows  
        rslt = db.query("select text from tb_test")  
        while row = rslt.fetch_row do  
            puts row[0]  
        end  
    rescue Mysql::Error => e  
            puts "Error code: #{e.errno}"  
            puts "Error message: #{e.error}"  
            puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")  
    ensure  
            db.close if db  
    end
  • redis
#!/bin/ruby
    
    require 'redis'
    
    def writeToFile(file,content)
        fp = File.new(file,"a+") 
        if fp
            fp.syswrite(content)
        else
            puts "..."
        end
    end
    
    def connect(host)
        redis = Redis.new(:host => host,:port => 6379)
        redis.info.keys.each do |key|
            puts "#{key}:\t"+redis.info["#{key}"]
        end
    end
    
    connect("1.1.1.1")
  • sqlite3
require 'sqlite3'
    
    db = SQLite3::Database.new('test.db')
    
    db.execute("create table test(
                    ID integet not null,
                    Username varchar(20) null,
                    Password varchar(64) null)")
    db.execute("insert into test(ID.Username,Password) 
        values('0','admin','admin')")
    db.execute("select * from test")
    db.execute("update test set password='12345' where id=0")

3.Ruby socket

  • 服務端:
require 'socket'
    
    server = TCPServer.open('0.0.0.0', 8080)
    loop do
        Thread.start(server.accept) do |client|
            begin
                while true
                    puts "#{client.to_i} online"
                    data = client.read()
                    throw "empty" if data.empty?
                    #puts data.length
                    puts data
                end
            rescue Exception => e
                puts "#{client.to_i} offline"
            end
        end
    end
  • 客戶端:
require 'socket'
    
    hostname = '127.0.0.1'
    port = 8080
    buf = 'test'
    s = TCPSocket.open(hostname, port)
    s.write buf
    sleep(1)
    s.close

4.ruby gem 文檔服務

rubygems.org上的gem文檔訪問起來太慢了,其實gem自己就自帶doc的功能
安裝gem的時候會默認安裝相應gem的doc,若是不想佔用空間安裝doc,則gem install XXX --no-doc 便可。
使用下列命令能夠啓動gem自帶的文檔:mysql

gem server --port 1234

而後訪問http://localhost:1234就能夠查看相關的gem文檔。redis

5.ruby改變控制檯輸出內容的顏色

puts "\033[1m前景色\033[0m\n"  
    puts "   \033[30mBlack (30)\033[0m\n"  
    puts "   \033[31mRed (31)\033[0m\n"  
    puts "   \033[32mGreen (32)\033[0m\n"  
    puts "   \033[33mYellow (33)\033[0m\n"  
    puts "   \033[34mBlue (34)\033[0m\n"  
    puts "   \033[35mMagenta (35)\033[0m\n"  
    puts "   \033[36mCyan (36)\033[0m\n"  
    puts "   \033[37mWhite (37)\033[0m\n"  
    puts ''   
    puts "\033[1m背景色\033[0m\n"  
    puts "   \033[40m\033[37mBlack (40), White Text\033[0m\n"  
    puts "   \033[41mRed (41)\033[0m\n"  
    puts "   \033[42mGreen (42)\033[0m\n"  
    puts "   \033[43mYellow (43)\033[0m\n"  
    puts "   \033[44mBlue (44)\033[0m\n"  
    puts "   \033[45mMagenta (45)\033[0m\n"  
    puts "   \033[46mCyan (46)\033[0m\n"  
    puts "   \033[47mWhite (47)\033[0m\n"  
    puts ''  
    puts "\033[1m其餘\033[0m\n"  
    puts "   Reset (0)"  
    puts "   \033[1mBold (1)\033[0m\n"  
    puts "   \033[4mUnderlined (4)\033[0m\n"

6.一些比較特別的包

Ruby json gem
https://rubygems.global.ssl.fastly.net/gems/json-1.8.3.gem
樹莓派wiringpi gpio包
http://pi.gadgetoid.com/article/wiringpi-as-a-ruby-gemsql

7.安裝rvm的正確姿式

參考自:http://rvm.io/rvm/install
首先添加gpg公鑰:數據庫

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

安裝穩定版本的rvmjson

curl -sSL https://get.rvm.io | bash -s stable --ruby

8.解決kali2.0中RVM不能編譯ruby-2.3.3

  • 錯誤詳情:
ruby-2.3.3 - #compiling.......................................................................-
Error running '__rvm_make -j4',
showing last 15 lines of /usr/local/rvm/log/1488041042_ruby-2.3.3/make.log
exts.mk:210: recipe for target 'ext/openssl/all' failed
make[1]: *** [ext/openssl/all] Error 2
make[1]: *** Waiting for unfinished jobs....
installing default nkf libraries
compiling objspace_dump.c
linking shared-object json/ext/generator.so
make[2]: Leaving directory '/usr/local/rvm/src/ruby-2.3.3/ext/json/generator'
linking shared-object objspace.so
make[2]: Leaving directory '/usr/local/rvm/src/ruby-2.3.3/ext/objspace'
linking shared-object nkf.so
make[2]: Leaving directory '/usr/local/rvm/src/ruby-2.3.3/ext/nkf'
make[1]: Leaving directory '/usr/local/rvm/src/ruby-2.3.3'
uncommon.mk:203: recipe for target 'build-ext' failed
make: *** [build-ext] Error 2
++ return 2
There has been an error while running make. Halting the installation.

查看/usr/local/rvm/log/1488041042_ruby-2.3.3/make.log發現是openssl版本過老致使的。數組

  • 解決:
    第一步:先安裝用於rvm的openssl:
rvm pkg install openssl

第二步:編譯安裝ruby,指定openssl目錄(個人是/usr/local/rvm/usr/)ruby

rvm install ruby-2.3.3 --with-openssl-dir=/usr/local/rvm/usr/

9.設置Gems默認源爲ruby-china

如今沒有淘寶源了,只有ruby-china源bash

gem sources --add https://gems.ruby-china.org/ --remove https://rubygems.org/

設置Bundler默認源爲ruby-china:curl

bundle config mirror.https://rubygems.org https://gems.ruby-china.org

這樣修改之後,即便Gemfile中指定了Source,也會用國內的源。socket

相關文章
相關標籤/搜索