ruby memo


Hello.rb

#! /usr/bin/ruby
puts "Hello World!"

argument

# foo.rb aaa bbb ccc

arg1 = ARGV[0]			# "aaa"
arg2 = ARGV[1]			# "bbb"
arg3 = ARGV[2]			# "ccc"
arg_count = ARGV.size		# 3

work

wk = "ABCDEF"
ch = wk[0]			# "A"
ch_code = ch.ord		# 65
ch = ch_code.chr		# "A"

substr = wk[2..3]		# "CD"
substr = wk[2,3]		# "CDE"

str = "wk is #{wk}"		# "wk is ABCDEF"
str = 'wk is #{wk}'		# "wk is #{wk}"

array

array = [ "aaa", "bbb", "ccc" , "ddd", "eee", "fff" ]
array[0]		# "aaa"
array[2..4]		# [ "ccc" , "ddd", "eee" ]
array[2,3]		# [ "ccc" , "ddd", "eee" ]
array.size		# 6

array = []
array[0] = "aaa"
array[1] = "bbb"
array[2] = "ccc"

hash

hash = { "key1" => "data1", "key2" => "data2", "key3" => "data3" }
hash["key1"]		# "data1"

hash = {}
hash["key1"] = "data1"
hash["key2"] = "data2"
hash["key3"] = "data3"

operator

amari = puts 12 % 5		# 2
bekijou = puts 2 ** 3		# 8

if

wk1 = 10
wk2 = 20

if (wk1 == wk2)
	puts "#{wk1} == #{wk2}"
elseif (wk1 > wk2)
	puts "#{wk1} > #{wk2}"
else
	puts "#{wk1} < #{wk2}"		# true
end

if (wk1 != wk2)
	puts "#{wk1} != #{wk2}"		# true
else
	puts "#{wk1} == #{wk2}"
end

wk = "abcdef"
if (/^a.*f$/ =~ wk)
	puts "true"
else
	puts "false"
end

case

wk = 10
case wk
when 5
	puts "five"
when 10
	puts "ten"		# true
when 15
	puts "fifteen"
else
	puts "many"
end

while

i = 0
while (i < 5)
        puts i
        i += 1
end

for

array = [ "bbb", "aaa", "ccc" ]
for i in array
	puts i
end

for i in array.sort
	puts i
end

for i in 0..2
	puts array[i]
end

hash = { "key2" => "data2", "key1" => "data1", "key3" => "data3" }
for i in hash.keys
	puts hash[i]
end

for i in hash.keys.sort
	puts hash[i]
end

each

array = [ "aaa", "bbb", "ccc" ]
array.each do |i|
	puts i
end

hash = { "key1" => "data1", "key2" => "data2", "key3" => "data3" }
hash.each do |key, val|
	puts key + "=>" + val
end

step

1.step(10, 3) do |i|
	puts i
end

gsub

wk1 = "ABCDEFG"
wk2 = wk1.gsub(/C.*E/, 'cde')
wk2				# "ABcdeFG"

wk1 = "ABCDEFG"
wk2 = wk1.gsub(/^AB(C.*E)FG/){"ab" + $1 + "fg"}
wk2				# "abCDEfg"

wk = "%41%42%43+%44%45%46"
wk = wk.tr("+", " ")
wk = wk.gsub(/%([0-9a-zA-Z][0-9a-zA-Z])/){$1.hex.chr}
wk				# "ABC DEF"

split

wk = "aaa,bbb,ccc"
array = wk.split(',')
array[0]			# "aaa"
array[2]			# "ccc"

wk = "aaa,bbb,ccc,ddd"
array = wk.split(',', 3)
array[1]			# "bbb"
array[2]			# "bbb,ccc"

string

wk = "abcabcabc"
wk.length			# 9
wk.index('abc')			# 0
wk.rindex('abc')		# 6

wk_str = "123"
wk_int = wk_str.to_i		# 123
wk_float = wk_str.to_f		# 123.0
wk_str = wk_float.to_s		# "123.0"

file(line)

f = open("junk.txt", "w")
f.puts("line1")
f.puts("line2")
f.puts("line3")
f.flush
f.close

f = open("junk.txt", "r")
while (r = f.gets)
        r = r.chomp
        puts r
end
f.close

file(random)

# -*- encoding: utf-8 -*-

f = open("junk.txt", "w")
f.write("line1")
f.write("line2")
f.write("line3")
f.close

f = open("junk.txt", "r")
f.pos = 5
r = f.read(5)
puts r + "\n"			# "line2"
f.close

file(character)

# -*- encoding: utf-8 -*-

work = "line1\nline2\nline3\n"
f = open("junk.txt", "w")
for i in 0..(work.length-1)
	f.putc(work[i])
end
f.close

f = open("junk.txt", "r")
while (ch = f.getc)
	print ch
end
f.close

STDIN, STDOUT, STDERR

STDOUT.puts("hogehoge")
STDERR.puts("hogehoge")
r = STDIN.gets

execute command

f = open("|ls -al|head -5", "r")
while (r = f.gets)
       puts r.chomp
end
f.close

`ls -al|head -5`.each_line do |i|
       puts i.chomp
end

io = IO.popen("cat -n", "r+")
io.puts("line1")
io.puts("line2")
io.puts("line3")
io.flush	# flushをするのが確実。
io.close_write	# ただし、起動プログラムの作りによるとclose_writeする必要がある。
r = io.gets
puts r
r = io.gets
puts r
r = io.gets
puts r
io.close

system("ls -al|head -5")

print

wk = "ABCDEFG"
puts wk
print wk + "\n"
printf("%s\n", wk)

trap

begin
	wk = 1 / 0
rescue => e
	puts "Exception -> #{e}"
	p e
else
	puts "No exception"
ensure
	puts "always will be done"
end

begin
	wk = 1 / 0
rescue ZeroDivisionError => e
	puts "Exception -> #{e}"
	p e
else
	puts "No exception"
ensure
	puts "always will be done"
end

filesystem

File.umask(022)
File.chmod(0777, "junk.txt")
File.rename("junk.txt", "junk2.txt")
File.unlink("junk2.txt")

File.exist?("junk.txt")
File.file?("junk.txt")
File.directory?("junk.txt")
File.readable?("junk.txt")
File.writable?("junk.txt")
File.executable?("junk.txt")
File.zero?("junk.txt")
File.size("junk.txt")

File.basename("/etc/named.conf", ".conf")	# "named"
File.dirname("/etc/named.conf")			# "/etc"
File.expand_path("./junk.txt")			# "/absolute_path/junk.txt"

Dir.mkdir("lock.dir", 0755)
Dir.rmdir("lock.dir")
array = Dir.glob("./*")
for i in array
        puts i
end
Dir.chdir("..")
Dir.pwd

dir = Dir.open("/")
while (name = dir.read)
	puts name
end
dir.close

function

def add(v1 = 10, v2 = 20)
        if ($Global_v1 && $Global_v2)
                ret = $Global_v1 + $Global_v2
        else
                ret = v1 + v2
        end
        return ret
end

puts add()			# 30
puts add(100, 200)		# 300

$Global_v1 = 1000
$Global_v2 = 2000
puts add()			# 3000

class

class MySwitch
	def initialize(sw = 0)
		@sw = sw
	end

	def turnOn()
		@sw = 1
	end

	def turnOff()
		@sw = 0
	end

	def isOn()
		return (@sw == 1)
	end

	def isOff()
		return !isOn()
	end
end

class MyToggleSwitch < MySwitch
	def initialize(sw = 0)
		super(sw)
	end

	def toggle()
		if (isOn())
			turnOff()
		else
			turnOn()
		end
	end
end

sw1 = MySwitch.new
if (sw1.isOn())
	puts "sw1 is On"
else
	puts "sw1 is Off"
end
sw1.turnOn()
if (sw1.isOn())
	puts "sw1 is On"
else
	puts "sw1 is Off"
end
sw1.turnOff()
if (sw1.isOn())
	puts "sw1 is On"
else
	puts "sw1 is Off"
end

sw2 = MyToggleSwitch.new
if (sw2.isOn())
	puts "sw2 is On"
else
	puts "sw2 is Off"
end
sw2.toggle()
if (sw2.isOn())
	puts "sw2 is On"
else
	puts "sw2 is Off"
end
sw2.toggle()
if (sw2.isOn())
	puts "sw2 is On"
else
	puts "sw2 is Off"
end

environment variable

path = ENV['PATH']

daytime

day = Time.now
puts day			# "2016-12-15 16:50:46 +0900"
puts day.year			# "2016"
puts day.month			# "12"
puts day.day			# "15"
puts day.hour			# "16"
puts day.min			# "50"
puts day.sec			# "46"
puts day.wday			# "4" -> Thu

day += (3 * 24 * 60 * 60)
puts day.wday			# "0" -> Sun

day = Time.local(2016,12,31,23,59,59)

kill

begin
Process.kill("TERM", 1234)
rescue Errno::ESRCH
       puts "no such process"
else
       puts "signal send ok"
ensure
end

nkf

require "nkf"
puts NKF.nkf("-S -X -e", "\x8a\xbf\x8e\x9a\x82\xc5\x82\xb7")	# "漢字です"

timeout

require "timeout"
begin
       timeout(3){
               sleep 10
       }
rescue Timeout::Error
       puts "timeout happened!"
else
       puts "10sec sleepd"
ensure
end

yield

def hoge(count)
	for i in 1..count
		yield(i, i*i)
	end
end

hoge(5) do |v1, v2|
	       puts "v1=#{v1}, v2=#{v2}"
end

client

require "socket"

s = TCPSocket.new("localhost", 12345)
s.sync = true
s.puts "#{ARGV[0]}"
print s.gets
s.puts "Q"

server

require 'socket'

def daemon
       if (pid = fork)
               exit 0
       end
       Process.setsid
       if (pid = fork)
               exit 0
       end
       Dir.chdir("/")
       File.umask(0000)
       STDIN.close
       STDOUT.close
       STDERR.close

       Signal.trap("SIGTERM"){
               exit 0
       }
       Signal.trap("SIGHUP"){
               exit 0
       }
       Signal.trap("SIGINT"){
               exit 0
       }
end

daemon

port = 12345

gs = TCPServer.open(port)
while true
  ns = gs.accept
#  p ns.peeraddr
  Thread.start(ns) do |s|
    s.sync = true
    while line = s.gets
      break if /^q/i =~ line
      line.chomp!
      s.puts "#{line.swapcase}"
    end
    s.close
  end
end

[更新] [戻る]
m-ito@myh.no-ip.org