Ruby

Basic

Get the path of script.

p __dir__

Get current directory.

p Dir.pwd

Escape html.

require "cgi/util"

CGI.escape_html("< > & \"") # => "&lt; &gt; &amp; &quot;"

Main block(which will be called only if you run this file).

if __FILE__ == $0
  # code
end

File

Write and read from file.

File.write('foo.txt','hello')
# => 5
File.read('foo.txt')
# => "hello"

Read file(for larger file).

File.foreach('foo.txt') do |line|
  puts line
end

Read as CSV.

require 'csv'

CSV.foreach("foo.csv",encoding:"cp932",col_sep:"\t") do |row|
  puts row
end

Get disk space via df command(without installing any gems).

def df(pat) # i.e. /dev/vda3
  res = `df -h | grep #{pat}`.strip
  res.split(/ +/)[1,4] # ["14G", "4.6G", "8.8G", "35%"]
end

Read and write JSON.

require 'json'

data = JSON.parse(File.read("foo.json"))
File.write("bar.json",JSON.pretty_generate(data))

Database

Mysql

To activate load data local .. on MySQL8.0, need to set local_infile: true.

client = Mysql2::Client.new(host: "localhost", username: "user", local_infile: true)
client.query("use db")
results = client.query("select * from t")
results.each do |row|
  puts row
end
client.close

Time(date)

Get current time.

Time.now.strftime("%F %T")
# => "2022-01-29 21:14:09"

Optparse

require 'optparse'

e = false # flag for execution
options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: foo.rb [-a foo] [-b bar] [-e]"
  opts.on("-a", "--apple foo", "Foo") { |v| options[:a] = v }
  opts.on("-b", "--banana bar", "Bar") { |v| options[:b] = v }
  opts.on("-e", "--execute", "Execute all commands.") { |v| e = true }
end.parse!

Geo3x3

require './geo_3x3'

lat, lng = 31.908714674017606, 131.42030837301505
level = 18
puts "#{lat},#{lng}"
geo = Geo3x3.encode(lat,lng,level)
puts geo
p Geo3x3.decode(geo)