ruby Ruby Code Snippets
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby Code Snippets相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env rspec
require "rspec"
def user_list(n,m)
x=n%m
y=n/m
z = Array.new(y,m)
z.push(x) if x > 0
z
end
describe "Default" do
it 'balh' do
expect(user_list(100,10)).to eq([10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
expect(user_list(101,10)).to eq([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1])
end
end
#!/usr/bin/env rspec
require "rspec"
def xxx(x)
x.each_slice(3).to_a
end
describe "Default" do
it 'balh' do
x= %w( a b c d e f g h i j k l m n o p )
expect(xxx(x)).to eq([])
end
end
#!/usr/bin/env ruby
module A
class << self
# This module variable can be shared across instances
# true singleton
attr_reader :blah
def inside_self
puts "inside self"
end
def blah_set(v)
@blah = v
end
def blah_access
puts self.blah
end
end
# End of self section
# this class will build its instance method around module functions above
# so module functions will keep track of @blah across instances of class B
class B
def initialize(v)
A.blah_set(v)
end
def show
A.blah_access
end
end
end
# first instance of A::B set @blah to 20
a = A::B.new(20)
a.show
# second instance of A::B set @blah to 30
b = A::B.new(30)
# now both instances has @blah set to 30
b.show
a.show
#!/usr/bin/env ruby
#
require 'logger'
def exception
out = nil
begin
out = yield
rescue Exception => e
Logger.new(STDOUT).error(e.message)
end
out
end
exception { exit(1) }
#https://betterexplained.com/articles/an-intuitive-guide-to-exponential-functions-e/
#!/usr/bin/env ruby
def backoff(seed)
n = seed
i = seed/10.0
lambda do
m = (( (1 + 1/n) ** n ) - 2)
n = n + i
m > 0 ? ( return m ) : ( return 0 )
end
end
blah = backoff(0.02)
cnt = 0
loop do
val = blah.call
cnt = cnt + 1
if val > 0
puts "count before non-zero value #{cnt}"
exit
end
# sleep 0.250
end
## INPUT
# reading from STDIN
STDIN.each_line do |l|
l.chomp!
end
# read file
File.open('att.csv', 'r') do |f|
puts f.read
end
# readline
File.readlines('filename').each do |l|
l.chomp!
end
# get input from command line
puts "you input"
in = gets
in.chomp!
# IO read like slurp
IO.read(filename)
# Read Yaml
require 'safe_yaml'
YAML.load(IO.read(file), :safe => true)
# Read json
JSON.parse(IO.read(file), symbolize_names: true)
# Write json
JSON.generate(hash)
## OUTPUT
# append into file
open('myfile.out', 'a') do |f|
f.puts "Hello, world. It's me again."
end
# write in file
File.open('/tmp/test.yml', 'w') {|f| f.write d.to_yaml }
# write with IO
IO.write(resource_path, "default_action :create")
#!/usr/bin/env ruby
require 'thor'
require 'logger'
require 'thread'
module ThreadpoolExample # :nodoc:
# Singleton
class << self
attr_accessor :logger
attr_accessor :verbose
def dry?
ENV['DRY'] ? true : false
end
def default_logger
v = ThreadpoolExample.verbose
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
logger.level = Logger::DEBUG if v
logger
end
def tty?
$stdout.tty?
end
end
#Threadpool
class ThreadPool
def initialize(size)
@size = size
@jobs = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.abort_on_exception = true
Thread.current[:id] = i
catch(:exit) do
loop do
job = @jobs.pop
job.call
end
end
end
end
if block_given?
yield self
shutdown
end
end
def schedule(&block)
@jobs << block
end
def shutdown
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
true
end
end
# Helpers
module Helper
def rand_sleep
t = rand(0...15)/10.0
ThreadpoolExample.logger.info("sleep time - #{t}")
sleep t
end
end
# CLI
class CLI < Thor
include Helper
def self.global_options
method_option :verbose,
aliases: ['-v', '--verbose'],
desc: 'Verbose',
type: :boolean,
default: false
end
desc 'start', 'Wrap both function one and two'
global_options
def start
threadpool_size = 2
ThreadPool.new(threadpool_size) do |pool|
ts = Time.now.to_i
# number of time loops through , this represent total size of work
(0...20).each do
begin
pool.schedule { rand_sleep }
rescue
ThreadpoolExample.logger.error("Command failed")
end
end
end
end
end
end
ThreadpoolExample.verbose = ENV['VERBOSE'] ? true : false
ThreadpoolExample.logger = ThreadpoolExample.default_logger
ThreadpoolExample::CLI.start(ARGV) if $PROGRAM_NAME == __FILE__
# Single Valued
print "Enter your grade: "
grade = gets.chomp
case grade
when "A"
puts 'Well done!'
when "B"
puts 'Try harder!'
when "C"
puts 'You need help!!!'
else
puts "You just making it up!"
end
# Multi Valued
print "Enter your grade: "
grade = gets.chomp
case grade
when "A", "B"
puts 'You pretty smart!'
when "C", "D"
puts 'You pretty dumb!!'
else
puts "You can't even use a computer!"
end
# Sum of array elements
x=[ 1, 2, 3, 4, 5 ]
x.inject(0){ |sum,s| sum + s }
# convert key value pair line into hash
x='level=DATA id=20180111231545 ts=1515721272.992468 jira=VIDDEVOPS-1670 region=us-west-1'
h = Hash[x.split(/\s+/).map {|it| it.split('=', 2)}]
# h should
# {"level"=>"DATA", "id"=>"20180111231545", "ts"=>"1515721272.992468", "jira"=>"VIDDEVOPS-1670", "region"=>"us-west-1"}
#Docstring - interpolation
my_str = <<-FOO
This is the first line.
This is the second line.
1 + 1 is #{1 + 1}.
FOO
# => "This is the first line.\nThis is the second line.\n1+1 is 2.\n"
# Note the *absence* of a leading newline character.
# %q - no interpolation
my_str = %q(
This is the first line.
This is the second line.
1 + 1 is #{1 + 1}.
)
# => "\nThis is the first line.\nThis is the second line\n1 + 1 is \#{1 + 1}.\n"
# Note the absence of interpolation.
# %Q - with interpolation
my_str = %Q(
This is the first line.
This is the second line.
1 + 1 is #{1 + 1}.
)
# => "\nThis is the first line.\nThis is the second line.\n1 + 1 is 2.\n"
require 'pty'
begin
PTY.spawn( "ruby random.rb" ) do |stdout, stdin, pid|
begin
stdout.each { |line| print line }
rescue Errno::EIO
end
end
rescue PTY::ChildExited
puts "The child process exited!"
end
#### OR
IO.popen('ruby random.rb') do |io|
while (line = io.gets) do
puts line
end
end
# Use Gists to store entire functions
class QuickSort
def self.sort!(keys)
quick(keys,0,keys.size-1)
end
private
def self.quick(keys, left, right)
if left < right
pivot = partition(keys, left, right)
quick(keys, left, pivot-1)
quick(keys, pivot+1, right)
end
keys
end
def self.partition(keys, left, right)
x = keys[right]
i = left-1
for j in left..right-1
if keys[j] <= x
i += 1
keys[i], keys[j] = keys[j], keys[i]
end
end
keys[i+1], keys[right] = keys[right], keys[i+1]
i+1
end
end
#!/usr/bin/env ruby
require 'mixlib/shellout'
require 'pp'
def parse_line(l, r=nil)
d = {}
c = l.match(r)
return false if c.nil?
r.scan(/\?\<(\w+)\>/).each { |k| d[k[0]] = c[k[0]] }
#pp c.class unless c.nil?
return d if d.keys.length > 0
end
data = []
cmd = Mixlib::ShellOut.new("./wrk -c 100 -t 38 -k https://web-0001.host:8443/4kb")
cmd.run_command
cmd.error!
cmd.stdout.split("\n").each do |l|
data << ( parse_line(l,'^Running (?<duration>\w+) test @ (?<url>[\w:/.-]+)/(?<size>\w+)$') ||
parse_line(l,'\s+(?<threads>\d+) threads and (?<connections>\d+) connections. session reuse:(?<reuse>\w+), keep-alive:(?<keepalive>\w+)') ||
parse_line(l,'\s+?Latency\s+?(?<latency_avg>[\w.]+)\s+?(?<latency_stdev>[\w.]+)\s+?(?<latency_max>[\w.]+)\s+?(?<latency_variation>[\w.]+%)') ||
parse_line(l,'\s+Req/Sec\s+(?<rps_avg>[\w.]+)\s+(?<rps_stdev>[\w.]+)\s+?(?<rps_max>[\w.]+)\s+?(?<rps_variation>[\w.]+%)') ||
parse_line(l,'\s+(?<total_request>\d+) requests in (?<total_time>[\w.]+), (?<total_transfer>[\w.]+) read') ||
parse_line(l,'Requests/sec:\s+(?<rps>[\w.]+)') ||
parse_line(l,'Transfer/sec:\s+(?<transfer>[\w.]+)') ||
parse_line(l,'TLS new conn (?<tls_new_conn>\d+) reused (?<tls_reused>\d+) miss (?<tls_miss>\d+) finished conn (?<tls_fin_conn>\d+) sess_cb_hit (?<tls_sess_cb_hit>\d+) renegotiation (?<tls_renegotiation>\d+) timeout (?<tls_timeout>\d+) full remove (?<tls_full_remove>\d+)') ||
parse_line(l,'\s+Non-2xx or 3xx responses: (?<non-2xx3xx>\w+)') ||
parse_line(l,'\s+Socket errors: connect (?<sock_conn_err>\d+), read (?<sock_read_err>\d+), write (?<sock_write_err>\d+), timeout (?<sock_timeout_err>\d+)') )
end
pp data
#!/usr/bin/env ruby
require 'pp'
opts = [
['./wrk'],
['--connections=100','--connections=200','--connections=300','--connections=400','--connections=500'],
['','--no_keepalive'],
['','--reuse '],
['--threads=38 '],
['--duration=10 '],
['http://web-0001.host:8080/',
'http://web-0002.host:8080/',
'https://web-0003.host:8443/',
'https://web-0004.host:8443/'],
['4kb','1mb']
]
$global = []
def build_cmd(a)
aa = []
bb = []
if a.length > 0
b = a.shift
b.each do |x|
$global.push(x)
build_cmd(a)
#bb.push($global.pop) if $global.length > 0
bb.push($global.pop)
end
a.unshift(bb)
else
puts $global.join(' ')
end
end
build_cmd(opts)
line = 'key1=val1 key2=val2 key3=val3 key4=val4 key5=val5 key6=val6 key7=val7 key8=val8 key9=val9 key10=val10 key11=val11 key12=val12 key13=val13 key14=val14 key15=val15 key16=val16 key17=val17 key18=val18 key19=val19 key20=val20 key21=val21 key22=val22 key23=val23 key24=val24 key25=val25 key26=val26 key27=val27 key28=val28 key29=val29 key30=val30 key31=val31 key32=val32 key33=val33 key34=val34 key35=val35 key36=val36 key37=val37 key38=val38 key39=val39 key40=val40 key41=val41 key42=val42 key43=val43 key44=val44 key45=val45 key46=val46 key47=val47 key48=val48 key49=val49 key50=val50 key51=val51 key52=val52 key53=val53 key54=val54 key55=val55 key56=val56 key57=val57 key58=val58 key59=val59 key60=val60 key61=val61 key62=val62 key63=val63 key64=val64 key65=val65 key66=val66 key67=val67 key68=val68 key69=val69 key70=val70 key71=val71 key72=val72 key73=val73 key74=val74 key75=val75 key76=val76 key77=val77 key78=val78 key79=val79 key80=val80 key81=val81 key82=val82 key83=val83 key84=val84 key85=val85 key86=val86 key87=val87 key88=val88 key89=val89 key90=val90 key91=val91 key92=val92 key93=val93 key94=val94 key95=val95 key96=val96 key97=val97 key98=val98 key99=val99 key100=val100'
m = Hash[*[line.split(/\s+/).map{|e| e.split(/=/) }].flatten]
puts m
#!/usr/bin/env ruby
require 'csv'
require 'pp'
csv_file = ARGV.shift
att = CSV.read(csv_file, :headers => true )
# individual row
#puts att['timestamp']
att.headers.each do |h|
a = att[h]
a.unshift(h)
puts a.join(' ')
end
class StackArray < Array
def initialize(limit)
@limit = limit
end
def stackpush(i)
self.push(i)
while self.length > @limit do
self.shift
end
end
end
x = StackArray.new(5)
x.stackpush('a')
x.stackpush('b')
x.stackpush('c')
x.stackpush('d')
x.stackpush('e')
x.stackpush('f')
x.stackpush('g')
x.stackpush('h')
# this will keep empty array from top
puts x # [d e f g h]
# store string wth %Q()
my_str = %Q(
This is the first line.
This is the second line.
1 + 1 is #{1 + 1}.
)
# => "\nThis is the first line.\nThis is the second line.\n1 + 1 is 2.\n"
#!/usr/bin/env ruby
# http://www.andrewhavens.com/posts/20/beginners-guide-to-creating-a-rest-api/
# http://www.sitepoint.com/uno-use-sinatra-implement-rest-api/
require 'sinatra'
require 'json'
require 'pp'
class Foo
attr_accessor :data
def initialize
@data = {
'abhisawa' => 'blah blah',
'jithin' => 'aa aa'
}
end
def list
JSON.pretty_generate(@data)
end
def get(k)
JSON.pretty_generate({ k => @data[k] }) if @data.has_key?(k)
end
def create(h)
@data.merge!(h)
end
end
n = Foo.new
# curl http://localhost:4567/list
get '/list' do
n.list
end
# curl http://localhost:4567/get?k=param1
get '/get' do
if params.has_key?('k')
n.get(params['k']) || '{}'
else
return status 400
end
end
# curl http://localhost:4567/create -d 'param1=value1¶m2=value2'
post '/create' do
n.create(params)
return status 201
end
#HTTP Status Codes
#
#2xx = Success
#3xx = Redirect
#4xx = User error
#5xx = Server error
#Here's a list of the most important status codes:
#
#Success codes:
#
#200 - OK (the default)
#201 - Created
#202 - Accepted (often used for delete requests)
#User error codes:
#
#400 - Bad Request (generic user error/bad data)
#401 - Unauthorized (this area requires you to log in)
#404 - Not Found (bad URL)
#405 - Method Not Allowed (wrong HTTP method)
#409 - Conflict (i.e. trying to create the same resource with a PUT request)
class Template #:nodoc:#
include ERB::Util
attr_accessor :data, :template
def initialize(data, template)
@data = data
@template = template
end
def render
ERB.new(@template, nil, '-').result(binding)
end
def save(file)
File.open(file, 'w+') { |f| f.write(render) }
end
end
data = {
:key1 => val1,
:key2 => val2
}
tmpl='
"count": <%=data[:key1]%>,
"started_by": "<%=data[:key2]%>'
def render_tmpl(data, tmpl)
t = Template.new(data,tmpl)
t.render
end
class RecursiveHash < Hash
def initialize
recurse_hash = proc { |h,k| h[k] = Hash.new(&recurse_hash) }
super(&recurse_hash)
end
end
require 'mixlib/shellout'
module My
# @author
module ShellOut
# @return [Mixlib::ShellOut]
def shell_out(*command_args)
cmd = Mixlib::ShellOut.new(*command_args)
if STDOUT.tty?
cmd.live_stream = STDOUT
end
cmd.run_command
cmd
end
# @return [Mixlib::ShellOut]
def shell_out!(*command_args)
cmd = shell_out(*command_args)
cmd.error! # raise exception if existstatus is non-zero
cmd
end
end
end
# Shorter version
def shellout!(*c)
cmd = Mixlib::ShellOut.new(*c)
cmd.run_command
cmd.error!
cmd.stdout
end
以上是关于ruby Ruby Code Snippets的主要内容,如果未能解决你的问题,请参考以下文章
ruby 生成ruby.rack.status_code.snip