【Ruby】基础整理

1.在cmd下进入ruby解释器环境

cmd-》输入irb

2.获取当前文件路径

File.dirname(__FILE__)

3.Ruby web请求

http get请求:

    #加载模块
    require 'net/https'
    require 'uri'
    require 'json'
    
    para = {}
    para["user"] = 'root'
    url = 'http://www.XXX.com'
    uri = URI.parse(url)
    res = Net::HTTP.post_form(uri, para)
    
    resbody = JSON.parse(res.body)

http post 请求:

require 'net/https'
require 'uri'
require 'json'

para = {}
para["user"] = 'root'
url = 'http://www.XXX.com'
uri = URI.parse(url)
header={'Content-Type' => 'application/json'}
req = Net::HTTP::Post.new(uri.path, header)
req.body = para.to_json

res = Net::HTTP.new(uri.host, uri.port).start{|http|
    http.request(req)
}
resbody = JSON.parse(res.body)

http REST类型请求获取cookie:

  require 'net/https'
  require 'uri'
  require 'json'
                
  uri=URI.parse(url)
  para={}
  para=["user"]="root"
  res==Net::Http.post_form(uri,para)
  head_hash=res.to_hash
  if !head_hash.keys.include?("set-cookie")
       puts "Rest类型借口登录认证失败"
  end
  head_hash.keys.each{|key|
        if key =="set-cookie"
        	return head_hash["set-cookie"]
        end
  }

4.把两个数组一一对应成哈希

m=[a,b,c]
n=[1,2,3]
hash1={}
m.each_with_index{|para,value|
	hash1[para]=value
}

5.把字符串数值范围转化为值

例如:给定字符串范围“1-30”

a=[]
for i in 1..30
	a<<i
end

6.并行操作

threads=[]
code =lambda{
	执行1
	执行2
}
theards<<Theard.new(&code)
theards.each do|t|
	t.join
end

猜你喜欢

转载自blog.csdn.net/qq_35061334/article/details/87534489