Skip to content

Instantly share code, notes, and snippets.

@dhirabayashi
Last active August 5, 2018 13:34
Show Gist options
  • Save dhirabayashi/e7d760754ccf365431f64c986a5ccf0d to your computer and use it in GitHub Desktop.
Save dhirabayashi/e7d760754ccf365431f64c986a5ccf0d to your computer and use it in GitHub Desktop.
x = 1
while x <= 9
y = 1
while y <= 9
print x.to_s + " × " + y.to_s + " = " + (x * y).to_s
print "\t"
y += 1
end
x += 1
print "\n"
end
hash = {}
dup = []
File.foreach('C:\program1\result2.txt') do |line|
if hash.has_key?(line) then
dup << line unless dup.include?(line)
else
hash[line] = nil
end
end
File.open('C:\program1\result3.txt', 'w') do |file|
dup.each do |i|
file.print i
end
end
class Hello
attr_accessor:name
def initialize
@name = "detteiu"
end
def say
puts "Hello," + @name + "!"
end
end
obj = Hello.new
puts obj.name
obj.name = "luigi"
obj.say
print "年齢を教えてください >"
age = STDIN.gets.chomp.to_i
if age < 0 then
puts "未来人ですか?"
else
days = age * 365
puts "あなたが生まれてからたぶん" + days.to_s + "日くらい経ちます"
end
a = (1..100).to_a
a.each do |item|
puts item
end
a2 = (1..100).to_a
a2.collect! {|item| item * 100}
a2.each {|item| puts item}
a = (1..100).to_a
a3 = []
a.each do |item|
a3 << item if item % 3 == 0
end
a3.each {|item| puts item}
puts
a.delete_if {|item| item % 3 != 0 }
a.each {|item| puts item}
a = (1..100).to_a
a.reverse!
a.each {|item| puts item}
a = (1..100).to_a
sum = 0
a.each do |item|
sum += item
end
puts sum
ary = (1..100).to_a
result = []
10.times do |i|
result << ary[(i * 10)..(i * 10 + 9)]
end
p result
def sum_array(num1, num2)
if num1.size != num2.size then
return nil
end
array = []
num1.each_with_index do |item, i|
array[i] = num1[i] + num2[i]
end
return array
end
p sum_array([1, 2, 3], [4, 6, 8])
array = ["aaa", "bbb"]
puts array[0]
array[2] = "ccc"
puts array[2]
array = ["aaa", "bbb"]
a, b = array
puts a + b
array = Array.new
array[0] = "aaa"
array[1] = "bbb"
array[2] = "ccc"
array.each { | e |
puts e
}
array = Array.new(2)
array[0] = "aaa"
array[1] = "bbb"
array[2] = "ccc"
array[3] = "ddd"
array.each { |e|
puts e
}
array = (0..100).to_a
puts array[0, 4].join(', ')
puts array[0..4].join(', ')
(1..100).each do |n|
puts case 0
when n % 15 then :FizzBuzz
when n % 3 then :Fizz
when n % 5 then :Buzz
else n
end
end
def check(param)
if param then
return "真"
else
return "偽"
end
end
puts check(true) #真
puts check(false) #偽
puts check(nil) #偽
puts check(0) #真
puts check(111) #真
puts check(1.5) #真
puts check("aaa") #真
class Box
def open
puts 'よくわかんないけどとりあえず開ける'
end
end
box1 = Box.new
box2 = Box.new
box3 = Box.new
box4 = Box.new
def box1.open
puts '開ける'
end
def box2.open
puts '解錠して、ふたを開ける'
end
def box3.open
puts 'リボンを解いて、ふたを開ける'
end
list = []
list << box1
list << box2
list << box3
list << box4
list.each do |box|
box.open
end
while true
puts "\nそんな装備で大丈夫か?\n"
puts "1. 大丈夫だ、問題ない"
puts "2. 一番いいのを頼む"
answer = STDIN.gets
if answer == nil then
next
end
case answer.chomp
when "1"
puts "\n神は言っている、ここで死ぬ運命ではないと\n"
when "2"
puts "\n神は言っている、全てを救えと"
puts "オトートノカタキヲトルノデス"
break
end
end
puts "数値を2つ入力してください"
x = STDIN.gets.chomp.to_i
y = STDIN.gets.chomp.to_i
puts "2つ値の和:" + (x + y).to_s
def call_each(array, &block)
array.each(&block)
end
array = (1..10).to_a
call_each(array) do |i|
puts i
end
puts "今何月ですか?"
month = STDIN.gets
if month == nil
puts "ぬるぽ"
exit
end
month = month.chomp.to_i
case month
when 1..2
puts "冬ですね"
when 3..5
puts "春ですよー"
when 6..8
puts "夏真っ盛り"
when 9..11
puts "俺たちの秋はこれからだ!"
when 12
puts "年末なので来年からほんきをだす"
else
puts "そんな月ありません"
end
# 自分の得意な言語で
# Let's チャレンジ!!
s = gets.chomp
c_list = s.scan('c')
a_list = s.scan('a')
t_list = s.scan('t')
complete_count = 0
required_c_count = 0
required_a_count = 0
required_t_count = 0
array = Array.new([c_list.size, a_list.size, t_list.size].max)
array.zip(c_list, a_list, t_list) do |a|
sample = a.join
if sample == 'cat' then
complete_count += 1
else
required_c_count += 1 unless sample.include?('c')
required_a_count += 1 unless sample.include?('a')
required_t_count += 1 unless sample.include?('t')
end
end
puts complete_count
puts required_c_count
puts required_a_count
puts required_t_count
def cels2fahr(cels)
cels * 9 / 5 + 32
end
puts cels2fahr(28)
puts cels2fahr(10)
def camouflagedGIF?(filename)
flg = false
if /gif/i !~ filename.split(".").last
File.open(filename, "rb") do |file|
flg = file.read(3) == "GIF"
end
end
return flg
end
require "find"
Find.find('/hoge') do |path|
if FileTest.file?(path) then
puts path if camouflagedGIF?(path)
end
end
list = Dir.glob('./img/*')
list.each do |file|
new_file = file.sub("\n", '')
File.rename(file, new_file)
end
require 'socket'
host = ARGV[0]
path = ARGV[1] || '/'
s = TCPSocket.new(host, 80)
s.print "GET #{path} HTTP/1.0\nHost: #{host}\n\n"
print s.read
class C
def test
puts "test"
end
def myupcase(str)
return str.upcase
end
end
c = C.new
c.test
puts c.myupcase("aaa")
class C
def set_value(arg)
@value = arg
end
def get_value
return @value
end
end
c = C.new
c.set_value("aaa")
puts c.get_value
require 'socket'
print TCPSocket.open('localhost', 12345).read
class C
Const = 3
end
puts C::Const
puts ::C::Const
require "fileutils"
FileUtils.copy_entry('C:\foo', 'C:\bar')
#encoding : Windows-31J
require 'fileutils'
def copyFile(src, dest)
Dir.chdir(src)
Dir.glob('*') do |file|
if FileTest.directory?(file) then
destDir = dest + '/' + file
Dir.mkdir(destDir)
copyFile(Dir.pwd + '/' + file, destDir)
else
path = src + '/' + file
puts path
FileUtils.copy(path, dest + '/' + file)
end
end
Dir.chdir('..')
end
src = 'C:¥foo'
dest = 'C:¥bar'
copyFile(src, dest)
#encoding : Windows-31J
require 'fileutils'
FileUtils.cp_r('C:¥foo', 'C:¥bar')
#encoding: Windows-31J
dest = 'C:/foo/bar'.split('/')
def copy_name(start, dest)
Dir.chdir(start)
full = dest.join('/')
Dir.mkdir(full) unless Dir.exists?(full)
Dir.glob('*') do |file|
dest.push(file)
puts dest.join('/')
if File.directory?(file) then
copy_name(file, dest)
else
File.open(dest.join('/'), 'w'){|file|}
end
dest.pop
end
Dir.chdir('..')
end
unless ARGV[0] then
$stderr.puts 'エラー:ディレクトリ名を指定してください。'
exit
end
copy_name(ARGV[0], dest)
#encoding : Windows-31J
p Time.now
File.open 'test.txt', 'w' do |file|
1000000000.times do
file.print 'a'
end
end
p Time.now
require "CSV"
datas = CSV.read("test.csv")
datas.each do |row|
row.each do |column|
print column + "\t"
end
puts
end
require "CSV"
CSV.foreach("test.csv") do |row|
row.each do |column|
print column + "\t"
end
puts
end
require "CSV"
File.open('result.csv', 'w') do |file|
CSV.foreach('KEN_ALL.CSV') do |line|
file.puts line.join("\t")
end
end
require "CSV"
text = "あああ,いいい,ううう"
array = text.parse_csv
puts array
puts 111.class.name
puts 111.2.class.name
puts "111".class.name
puts '111'.class.name
puts true.class.name
puts false.class.name
method_name = ARGV[0]
define_method method_name do
puts "This method is #{method_name}"
end
alice
def parrot(word='でっていうwww')
puts word
end
parrot 'ヤッフーwww'
parrot 'マンマミーアwww'
parrot 'オーキードーキwwww'
parrot
#encoding: Windows-31J
require 'pathname'
unless ARGV[0] then
$stderr.puts 'エラー:ディレクトリを指定してください。'
exit
end
def del_files(path)
files = path.children
files.each do |file|
puts file.expand_path.to_s
if file.directory? then
del_files(file)
else
file.delete
end
end
path.rmdir
end
del_files(Pathname.new(ARGV[0]))
require "fileutils"
FileUtils.remove_entry('C:\hoge', true)
#encoding : Windows-31J
require 'fileutils'
def deleteFile(start)
Dir.chdir(start)
Dir.glob('*', File::FNM_DOTMATCH) do |file|
count = 0
if FileTest.directory?(file) then
if file != '.' && file != '..' then
deleteFile(file)
end
else
puts Dir.pwd + '/' + file
begin
FileUtils.remove(file)
rescue => e
count += 1
if count == 5 then
$stderr.puts e.message
exit
else
retry
end
end
end
end
Dir.chdir('..')
Dir.rmdir(start)
end
print 'input directory >'
input = STDIN.gets.chomp
deleteFile(input)
require 'find'
Find.find('C:/img/') do |path|
st = File.stat path
if st.size == 480 then
File.delete(path) if FileTest.file? path
end
end
require 'pathname'
def delete(path)
files = path.children
files.each do |f|
if f.file? then
puts f
f.unlink
else
delete(f)
end
end
puts path
path.unlink
end
start = '/hoge'
delete(Pathname.new(start))
def dice
(rand 6) + 1
end
def dice10
sum = 0
10.times do
sum += dice
end
sum
end
30.times do
puts dice
end
puts dice10
#encoding : Windows-31J
require './windlg'
d = WinDlgt.new("Windows-31J")
ofn = OPENFILENAME.new
ofn.sTitle = "名前を付けて保存"
ofn.sArFilter = [[ "テキスト(*.txt)", "*.txt"], ["すべて(*.*)", "*.*"] ]
ofn.iFilterIndx = 0
ofn.sIniDir = ENV["USERPROFILE"] + '¥Documents'
ofn.iFlags = OFN_OVERWRITEPROMPT
if d.getSaveFileName(ofn) != 0 then
puts ofn.sFnameFull
puts ofn.sFname
end
doraBirthday = Time.mktime(2112, 9, 3)
today = Time.now
remain = (doraBirthday - today) / 60 / 60 /24
puts "ドラえもん誕生まであと" + remain.to_s + "日くらいです"
unless ARGV[0] then
$stderr.puts "error : no file."
exit
end
hash = {}
File.foreach(ARGV[0]) do |file|
hash[file] = nil
end
hash.keys.each do |line|
puts line
end
array = ["aaa", "bbb", "ccc"]
array.each do |item|
puts item.upcase
end
hash = {"aaa" => "AAA", "bbb" => "BBB", "ccc" => "CCC"}
hash.each do |key, value|
puts key + " : " + value
end
input = $stdin.gets
puts input.encoding
def equals(str1, str2)
return str1 == str2
end
print '"hello"と入力してください >'
input = STDIN.gets.chomp
if equals(input, "hello") then
puts "入力値はhelloです。"
else
puts "入力値はhelloではありません。"
end
現在時刻は<%= Time.now.to_s %>です。
<% 3.times do |i| %>
<%= i %>
<% end %>
begin
if rand(2) == 1 then
raise
end
rescue => e
p e
retry
else
puts "異常なし"
ensure
puts "でっていう"
end
File.foreach('test.txt') do |line|
line.chomp!
puts line.sub(/(.*),(.*)/) {|s| "#{$2},#{$1}"}
end
require_relative 'Vessel'
v = Teapot.new('tea')
p v.pour_out
p v.pour_out
v = Teapot.new('coffee')
def fact(n)
if n < 1 then
raise 'n is under 1.'
end
if n == 1 then
return n
else
return n * fact(n - 1)
end
end
1.upto(20) do |i|
puts "fact(#{i}) = #{fact(i)}"
end
# coding: utf-8
require './cels2fahr.rb'
def fahr2cels(fahr)
(5 * fahr - 160) / 9
end
(1..100).each do |i|
puts "摂氏#{i}℃ = 華氏#{cels2fahr(i)}℃"
end
class Foo
def [](i)
self
end
def downcase
'dedededettteiu!'
end
end
def fetch_and_downcase(array, i)
if array[i] then
return array[i].downcase
end
end
array = ['AAA', 'BBB', 'CCC']
puts fetch_and_downcase(array, 1)
hash = {wario: 'MUWAAAAAA!', mario: 'UWAAAAAA!', luigi: 'HAHAHAHAHAHAHAAAAA!'}
puts fetch_and_downcase(hash, :wario)
puts fetch_and_downcase(Foo.new, 'test')
g = Fiber.new do |x|
loop { Fiber.yield(x); x += 1 }
end
5.times { puts g.resume(0) }
print "input file name >"
filename = STDIN.gets.chomp
print "search string >"
searchString = STDIN.gets.chomp
matchLines = Array.new
i = 0
File.foreach(filename) do |line|
if line.index(searchString) != nil then
matchLines[i] = line
i += 1
end
end
File.open("result.txt", "w") do |file|
matchLines.each do |line|
file.puts(line)
end
end
#encoding : Windows-31J
File.foreach "test.txt" do |line|
if /あ/ =‾ line then
puts line
end
end
(1..100).each do |i|
s = ""
s += "Fizz" if i % 3 == 0
s += "Buzz" if i % 5 == 0
s += i.to_s if s == ""
puts s
end
print "数値を入力してください >"
to = STDIN.gets.chomp.to_i
sum = 0;
for item in 1..to
sum += item
end
puts "1から入力値までの合計値は" + sum.to_s + "です"
for i in 1..10000 do
puts "#{i}番目のループ"
end
#encoding: Windows-31J
def gcd(x, y)
if y == 0 then
return x
else
return gcd(y, x % y)
end
end
print '1個目 >'
x = $stdin.gets.to_s.chomp.to_i
print '2個目 >'
y = $stdin.gets.to_s.chomp.to_i
if x < y then
x, y = y, x
end
puts "#{x}と#{y}の最大公約数は#{gcd(x, y)}"
#encoding: Windows-31J
Dir.glob('C:/img/**/*') do |file|
puts file
end
#encoding: Windows-31J
wday = {
Sunday: "日曜日",
Monday: "月曜日",
Tuesday: "火曜日",
Wednesday: "水曜日",
Thursday: "木曜日",
Friday: "金曜日",
Saturday: "土曜日"
}
puts wday.size
#encoding: Windows-31J
wday = {
Sunday: "日曜日",
Monday: "月曜日",
Tuesday: "火曜日",
Wednesday: "水曜日",
Thursday: "木曜日",
Friday: "金曜日",
Saturday: "土曜日"
}
wday.each do |key, value|
puts "「#{key}」は#{value}のことです。"
end
hash = Hash.new
hash["月曜日"] = "Monday"
hash["火曜日"] = "Tuesday"
hash["水曜日"] = "Wednesday"
hash["木曜日"] = "Thursday"
hash["金曜日"] = "Friday"
hash["土曜日"] = "Saturday"
hash["日曜日"] = "Sunday"
for item in hash
puts item[0] + " : " + item[1]
end
#encoding: Windows-31J
wday = {
Sunday: "日曜日",
Monday: "月曜日",
Tuesday: "火曜日",
Wednesday: "水曜日",
Thursday: "木曜日",
Friday: "金曜日",
Saturday: "土曜日"
}
puts wday
def test
puts "called"
end
map = {"test"=>test}
p map["test"]
map = {test: "test", aaa: "aaa", bbb: "bbb"}
map.each do |key, value|
puts "key=#{key}, value=#{value}"
end
puts "hello"
#!/usr/bin/env ruby
class Hello
@@count = 0
def initialize(name = 'Ruby')
@name = name
end
def self.count
@@count
end
def hello
@@count += 1
puts "Hello, #{@name}!"
end
end
puts Hello.count
bob = Hello.new('Bob')
alice = Hello.new('Alice')
ruby = Hello.new
bob.hello
alice.hello
ruby.hello
puts Hello.count
puts "Hello World!"
class Greeting
def hello
puts 'Hello Ruby World'
end
end
greet = Greeting.new
greet.hello
#encoding : Windows-31J
def myPrint(str)
puts str
end
myPrint('リボルケイン!')
def ruby
return 'Ruby'
end
puts ruby
#encoding : Windows-31J
def square(num)
num ** 2
end
print '数値を入力してください >'
input = $stdin.gets
# 数値変換
input = '' if input.nil?
input.chomp!
input = input.to_f
answer = square(input)
answer = answer.to_s
# 整数だったら後ろの.0を削除
if answer =‾ /^.*¥.0$/ then
answer = answer[0, answer.size - 2]
end
puts "入力値の2乗:#{answer}"
#encoding : Windows-31J
class Calculator
def add(x, y)
x + y
end
end
class Addition < Calculator
end
def getNum
input = $stdin.gets
input = '' if input.nil?
input.chomp!
input = input.to_i rescue 0
return input
end
calc = Addition.new
puts '整数を2つ入力してください(整数以外は0扱い)'
print '1つ目 >'
x = getNum
print '2つ目 >'
y = getNum
answer = calc.add(x, y)
puts "2つの整数の和は#{answer}です。"
#encoding : Windows-31J
def get_stdin_num
input = $stdin.gets
input = 0 if input.nil?
input = input.chomp.to_i rescue 0
return input
end
num = rand 2..10
numbers = []
puts "#{num}個の整数を入力してください(整数以外は0扱いとします)"
num.times do |i|
print i + 1, '個目 >'
numbers << get_stdin_num
end
sum = 0
numbers.each do |i|
sum += i
end
puts "入力値の一覧:#{numbers}"
puts "入力値の合計:#{sum}"
puts "入力値の平均:#{sum / numbers.size}"
i = 12
j = 4
puts "i + j = #{ i + j}"
puts "i - j = #{ i - j}"
puts "i × j = #{ i * j}"
puts "i ÷ j = #{ i / j}"
def myRand(num)
value = '';
num.times do
value += rand(10).to_s
end
return value
end
print '三桁:', myRand(3), "\n"
print '四桁:', myRand(4), "\n"
#encoding : Windows-31J
height = 13
char1 = ' '
char2 = '■'
height.times do |i|
i += 1
(height - i).times do
print char1
end
i.times do
print char2
end
puts char2
end
if ARGV.size == 0 then
STDERR.puts 'エラー:コマンドライン引数がありません。'
exit
end
print '入力値は'
ARGV.each do |value|
print "[ #{value} ]"
end
puts 'です。'
日本一高い山は?(漢字3文字) 富士山
ドラえもんの好きな食べ物は?(ひらがな4文字) どらやき
ロシアの首都は?(カタカナ4文字) モスクワ
#encoding : Windows-31J
#問題の読み込み
require 'csv'
csv = CSV.read('home6.csv')
quiz = csv[rand(csv.size)]
puts "問題:#{quiz[0]}"
print "回答 >"
answer = quiz[1]
input = $stdin.gets
input = '' if input.nil?
input.chomp!
if input == answer then
puts "正解"
else
puts "不正解"
puts "答え:#{answer}"
end
#encoding : Windows-31J
taxRate = 0.08
puts "消費税を計算します。(税率#{(taxRate * 100).to_i}%)"
print '金額 >'
#計算前の値入力
price = $stdin.gets
price = price.chomp.to_i rescue 0
#入力値チェック
if price <= 0 then
$stderr.puts 'エラー:1以上の整数を入力してください。'
exit
end
# 計算
tax = (price * taxRate).to_i
puts "税抜価格:#{price}円"
puts "消費税 :#{tax}円"
puts "税込価格:#{price + tax}円"
#encoding : Windows-31J
def get_stdin
input = $stdin.gets
input = '' if input.nil?
return input.chomp
end
answerTable = {}
answerTable['A'] = false
answerTable['B'] = true
answerTable['C'] = false
answerTable['D'] = false
while true do
puts
puts '問題:プログラミング言語Rubyの設計者は?'
puts 'A:ラリー・ウォール'
puts 'B:まつもとゆきひろ'
puts 'C:デニス・リッチー'
puts 'D:ジェームズ・ゴスリン'
puts
#入力
print '回答 >'
input = get_stdin
#回答判定
answer = answerTable[input]
if answer.nil? then
$stderr.puts 'エラー:A〜Dで解答してください。'
next
end
puts 'ファイナルアンサー?'
puts 'Yes > 1'
puts 'No > それ以外'
if get_stdin != '1' then
next
end
sleep 5
if answer then
puts '正解!'
else
puts '残念!'
puts '答え:B:まつもとゆきひろ'
end
break
end
class TestData
attr_accessor:str
def initialize
@str = 'Hello Ruby'
end
end
data = TestData.new
puts data.str
require 'win32ole'
def get_body(uri)
ie = WIN32OLE.new('InternetExplorer.Application')
ie.visible = true
ie.navigate(uri)
while ie.busy do
sleep 0.5
end
s = ie.document.body.innerText
ie.quit
return s
end
File.foreach('uris.txt') do |uri|
File.open('input.txt', 'a') do |file|
file.puts(get_body(uri))
end
end
module M
def test
puts "test"
end
end
class C
include(M)
end
C.new.test
class Super
def hello
puts "hello"
end
end
class Sub < Super
end
c = Sub.new
c.hello
class Hello
def initialize(name = "merio")
@name = name
end
def say
puts "Hello, " + @name + "!"
end
end
h = Hello.new("detteiu")
h.say
h = Hello.new
h.say
#!/usr/env ruby
nums = [43,54,32,53,2,11]
p nums.inject(0){ |sum, i| sum += i}
p nums.inject(:+)
#encoding:Windows-31J
puts "キングストーンと入力しなさい"
while STDIN.gets.chomp != "キングストーン" do
puts "入力値が違う"
end
class Integer
def to_ks
str = self.to_s
kstr = ''
kn = ['〇','一','二','三','四','五','六','七','八','九']
str.chars do |c|
kstr += kn[c.to_i]
end
return kstr
end
end
n = 12300
puts(n.to_s)
puts(n.to_ks)
print 'please input a string here >'
p gets
while line = gets do
puts "** #{line.chomp} **"
end
file = File.open('wonderland.txt', 'r')
file.each do |line|
puts "** #{line.chomp} **"
end
file.close
File.open('wonderland.txt', 'r') do |file|
file.each_line do |line|
puts "** #{line.chomp} **"
end
end
File.open("teapot.txt", "w") do |file|
file.print("darjeeling tea\n")
file.puts("assam tea")
file.printf("%s\n", "ceylon tea")
end
$stdin.each.with_index(1) do |line, i|
puts "#{i}: #{line.chomp}"
end
#encoding : Windows-31J
array = ["あああ", "いいい", "ううう"]
array.each { |i|
puts i
}
#encoding : Windows-31J
puts '0〜50までの中の3の倍数'
print '[ '
(0..50).each do |i|
print i, ' ' if i % 3 == 0
end
puts ']'
#encoding : Windows-31J
class NumData
attr_reader :value
def initialize(num)
@value = num
end
def double
return @value * 2
end
def square
return @value ** 2
end
end
answers = []
(0..9).each do |i|
answers << NumData.new(i)
end
answers.each do |num|
puts "#{num.value}の2倍は#{num.double}、2乗は#{num.square}です。"
end
#encoding : Windows-31J
# じゃんけんの手クラス
class Rps
attr_reader :hand, :flg
def initialize(flg)
case flg
when 1 then
@flg = 1
@hand = 'グー'
when 2 then
@flg = 2
@hand = 'チョキ'
when 3 then
@flg = 3
@hand = 'パー'
else
raise '値がおかしいです'
end
end
# 勝敗判定
# 勝った場合はtrue、負けた場合はfalse、あいこの場合はnilを返す
# 引数:rps 相手の手を表すRpsオブジェクト
def win?(rps)
# あいこ
return nil if @flg == rps.flg
# パーの場合
if @flg == 3 then
# 相手がグーなら勝ち
if rps.flg == 1 then
return true
else
return false
end
else
# グーかチョキの場合
# 相手が自分の手のフラグ + 1だったら勝ち
if @flg + 1 == rps.flg then
return true
else
return false
end
end
end
end
puts 'じゃんけん'
while true do
puts '1:グー'
puts '2:チョキ'
puts '3:パー'
puts
input = $stdin.gets.chomp
myHand = Rps.new(input.to_i)
puts 'ぽん'
puts
pcHand = Rps.new(rand(1..3))
puts "あなたの手:#{myHand.hand}"
puts "PCの手:#{pcHand.hand}"
sleep 1
judge = myHand.win?(pcHand)
if judge.nil? then
puts 'あいこで'
redo
end
if judge then
message = '勝ち'
else
message = '負け'
end
puts "あなたの#{message}です"
break
end
i = 0
while i < 10 do
puts "あいうえお"
i += 1
end
j = 0
while j < 10 do
puts "かきくけこ"
j += 1
end
#encoding : Windows-31J
def get_num
input = $stdin.gets
input = '' if input.nil?
input = input.chomp.to_i rescue 0
return input
end
def check(num)
if num <= 0 then
$stderr.puts 'エラー:正の整数を入力してください。'
exit
end
end
def get_divisors(num)
divisors = []
(1..num).each do |i|
divisors << i if num % i == 0;
end
return divisors
end
puts '正の整数を2つ入力してください'
print '1つ目 >'
x = get_num
check(x)
print '2つ目 >'
y = get_num
check(y)
x_divisors = get_divisors(x);
y_divisors = get_divisors(y);
common_divisors = x_divisors & y_divisors
answer = common_divisors[-1]
puts "#{x}と#{y}の最大公約数は#{answer}です"
year = ARGV[0].to_i
leapYear = false
if year % 4 == 0 then
if year % 400 == 0 || year % 100 != 0 then
leapYear = true
end
end
puts leapYear ? "うるう年" : "うるう年でない"
puts "プログラムを開始します。終了の際は999を入力してください。"
while true do
print "番号を入力してください(1~4) >"
input = STDIN.gets
if input == nil then
puts "エラー:1~4までの番号を入力してください"
next
end
input = input.chomp.to_i
case input
when 1 then
puts "一が選択されました。"
when 2 then
puts "二が選択されました。"
when 3 then
puts "三が選択されました。"
when 4 then
puts "四が選択されました。"
when 999 then
puts "お疲れ様でした。"
break
else
puts "エラー:1~4までの番号を入力してください"
end
end
def chomp(str)
if str != nil && str.instance_of?(String) then
return str.chomp
end
return ""
end
def to_i(i)
if i == nil then
return nil
end
if /^-?\d+$/ =~ i.chomp then
return i.to_i
end
return nil
end
class Plus
def set_x(x)
@x = x
end
def set_y(y)
@y = y
end
def get_operation_name
return "加算"
end
def get_operator_string
return "+"
end
def get_answer
return @x + @y
end
end
class Minus
def set_x(x)
@x = x
end
def set_y(y)
@y = y
end
def get_operation_name
return "減算"
end
def get_operator_string
return "-"
end
def get_answer
return @x - @y
end
end
class Multiple
def set_x(x)
@x = x
end
def set_y(y)
@y = y
end
def get_operation_name
return "乗算"
end
def get_operator_string
return "×"
end
def get_answer
return @x * @y
end
end
class Divide
def set_x(x)
@x = x
end
def set_y(y)
@y = y
end
def get_operation_name
return "除算"
end
def get_operator_string
return "÷"
end
def get_answer
if @y == 0 then
return nil
end
return @x / @y
end
def get_rest
if @y == 0 then
return nil
end
return @x % @y
end
end
class Exit
def get_operation_name
return "終了"
end
end
puts "プログラムを開始します。終了の際は999を入力してください。"
while true do
menu = {"1"=>Plus.new, "2"=>Minus.new, "3"=>Multiple.new, "4"=>Divide.new, "999"=>Exit.new}
print "番号を入力してください。( "
for hash in menu
print hash[0] + ":" + hash[1].get_operation_name + " "
end
print ") >"
menuNumber = chomp(STDIN.gets)
if !menu.include?(menuNumber) then
puts "エラー:メニュー番号が不正です。"
next
end
if menuNumber == "999" then
puts "お疲れ様でした。"
break;
end
operation = menu[menuNumber]
puts menuNumber + ":" + operation.get_operation_name + "を行います。"
print "一番目の数値を入力してください >"
x = to_i(STDIN.gets)
if x == nil then
puts "エラー:数値を入力してください。"
next
end
print "二番目の数値を入力してください >"
y = to_i(STDIN.gets)
if y == nil then
puts "エラー:数値を入力してください。"
next
end
puts x.to_s + operation.get_operator_string + y.to_s
operation.set_x(x)
operation.set_y(y)
answer = operation.get_answer
if answer == nil then
puts "エラー:値が不正です。計算を実施できません。"
next
end
print "答えは[" + answer.to_s + "]"
if operation.instance_of?(Divide) then
print " 余り[" + operation.get_rest.to_s + "]"
end
puts "です。"
end
#encoding : Windows-31J
begin
s = nil
s = s.chomp
rescue => e
print 'Error:'
puts e
end
puts "1~入力値までの数に含まれる素数を表示します。"
print "2以上の正の整数を入力してください >"
input = STDIN.gets
if input == nil || !(input.chomp! =~ /^\d+$/) || input =~ /^[01]$/ then
puts "エラー:2以上の正の整数を入力してください。"
exit
end
num = input.to_i
primeNumList = Array.new
primeNumList.push(2)
i = 3
while i <= num do
prime = true
j = 3
while j < i do
if i % j == 0 then
prime = false
break
end
j += 2
end
if prime then
primeNumList.push(i)
end
i += 2
end
puts "1~" + num.to_s + "までに含まれる素数"
print "[ "
primeNumList.each do |item|
print item
print " "
end
puts "]"
#encoding : Windows-31J
i = 1
array = nil
while true do
puts "#{i}回目"
array = []
while array.size != 9 do
num = rand(1..9)
unless array.include?(num) then
array << num
end
end
if array[0] + array[1] + array[2] == 15 ¥
&& array[0] + array[3] + array[6] == 15 ¥
&& array[0] + array[4] + array[8] == 15 ¥
&& array[2] + array[5] + array[8] == 15 ¥
&& array[6] + array[7] + array[8] == 15 ¥
then
break
end
i += 1
end
puts '+---+---+---+'
puts "| #{array[0]} | #{array[1]} | #{array[2]} |"
puts '+---+---+---+'
puts "| #{array[3]} | #{array[4]} | #{array[5]} |"
puts '+---+---+---+'
puts "| #{array[6]} | #{array[7]} | #{array[8]} |"
puts '+---+---+---+'
# 自分の得意な言語で
# Let's チャレンジ!!
n, m = gets.split.map{|i| i.to_i}
s = []
n.times do
s << gets.chomp
end
target = s[m - 1]
s.delete_at(m - 1)
index = 0
loop do
range = 0..index
s.select! {|j| target[range] == j[range]}
break if s.empty?
index += 1
end
puts target[0..index]
(1..9).each do |i|
(1..9).each {|j| print "#{i} × #{j} = #{i * j}\t"}
puts
end
#encoding : Windows-31J
def grep(filename, pattern)
pattern = Regexp.new pattern
lineNumber = 0
File.foreach filename do |line|
lineNumber += 1
if pattern =‾ line then
puts "#{lineNumber}行目:#{line}"
end
end
end
#encoding: Windows-31J
array = []
File.foreach('C:\program1\result.txt') do |line|
if !line.chomp.empty? && !line.start_with?('─')
array << line
end
end
File.open('C:\program1\result2.txt', 'w') do |file|
array.each do |i|
file.print i
end
end
str = "Welcome\nto\nRuby!"
count = 0
str.lines do | line |
count += 1
puts count.to_s + ": " + line
end
loop do
puts "ruby"
end
map = {"a" => "aaa", "b" => "bbb", "c" => "ccc"}
puts map["a"]
array = [1, 2, 3, 4, 5]
puts array.map {|i| i * 2}
#encoding: Windows-31J
class Hello
def method_missing(method, *args)
if method.to_s.end_with?('=') then
str_method = method.to_s
self.instance_eval <<-"DOC"
def #{str_method}(value)
@#{str_method.chop} = value
end
def #{str_method.chop}
@#{str_method.chop}
end
DOC
self.send method, args[0]
else
nil
end
end
end
test = Hello.new
test.namae = 'でっていう'
puts test.methods
p test.namae
module M
def myupcase(str)
return str.upcase
end
def mydowncase(str)
return str.downcase
end
end
class C
include M
end
c = C.new
puts c.myupcase("aaa")
puts c.mydowncase("BBB")
module M
def hoge
return "hoge"
end
end
module M2
include M
def fuga
return "fuga"
end
end
class C
include M2
def foo
return "foo"
end
end
class C2 < C
def bar
return "bar"
end
end
c = C2.new
puts c.hoge
puts c.fuga
puts c.foo
puts c.bar
class C
def test
return "class"
end
end
module M
def test
return "module"
end
end
class C2 < C
include M
end
c = C2.new
puts c.test
module Sample
def self.hoge
puts "hoge"
end
end
Sample::hoge
Sample.hoge
require "find"
require "fileutils"
list = []
Find.find('C:\foo') do |file|
list.push file
end
i = 0
indexes = []
while i < 20 do
index = rand list.size
if !indexes.include?(index) then
indexes.push index
i += 1
end
end
indexes.each do |item|
tmp = list[item].split("/")
filename = tmp[tmp.size - 1]
FileUtils.mv(list[item], 'C:\bar/' + filename)
end
# encoding: Windows-31J
require 'fileutils'
dir = 'C:/tmp/'
imgs = Dir.entries(dir)
targets = imgs.sample(100)
targets.each do |i|
FileUtils.mv(dir + i, i);
end
#encoding: Windows-31J
require 'fileutils'
from = 'C:/tmp/'
files = Dir.entries(from)
def files.my_sample(num)
if self.length <= num then
return self
end
set = {}
while set.length != num do
set[self[rand(self.length)]] = nil
end
return set.keys
end
files = files.my_sample(100)
files.each do |file|
FileUtils.mv(from + file, file)
end
puts (1..40).to_a.select {|x| x %3 == 0 || x.to_s.index('3')}
class Integer
def aho?
self % 3 == 0 || self.to_s.index('3')
end
end
puts (1..40).to_a.select{|x| x.aho?}
class C
class C2
class C3
Const = 3
puts Const
end
end
end
puts C::C2::C3::Const
5.times do
puts 'Hello World!'
end
n = ARGV[0].to_s.to_i
n.times do |i|
puts "Hello World! #{i + 1}"
end
def fizz_buzz(n)
ret = "#{"Fizz" unless (n % 3).nonzero?}#{"Buzz" unless (n % 5).nonzero?}"
ret.empty? ? n.to_s : ret
end
puts (1..100).collect{|n| fizz_buzz n }
def prime?(n)
# 2は素数
return true if n == 2
# 2より小さいか、2以外の偶数は素数ではない
return false if (n < 2) || n.even?
3.step(n - 1, 2) do |i|
return false if n % i == 0
end
return true
end
n = ARGV[0].to_s.to_i
exit unless n
puts "#{n}は素数#{prime?(n) ? 'です' : 'ではありません'}"
def prime?(n)
# 2は素数
return true if n == 2
# 2より小さいか、2以外の偶数は素数ではない
return false if (n < 2) || n.even?
3.step(n - 1, 2) do |i|
return false if n % i == 0
end
return true
end
n = ARGV[0].to_s.to_i
exit unless n
1.upto(n) do |i|
puts i if prime?(i)
end
puts nil.class.name
a = nil
#a.test_method
class NilClass
def test_method
puts 'test_method called.'
end
end
a.test_method
def a.test_method2
puts 'test_method2 called.'
end
a.test_method2
#摂氏温度を華氏温度に変換
def cels2fahr(cels)
if cels < -273 then
return nil
end
cels * 9 / 5 + 32
end
temp = 28
puts "今日の気温は摂氏#{temp}℃です。"
puts "華氏に直すと#{cels2fahr(temp)}°です。"
#華氏温度を摂氏温度に変換
def fahr2cels(fahr)
if fahr < -459 then
return nil
end
(fahr * 5 - 160) / 9
end
#摂氏温度を華氏温度に変換
def cels2fahr(cels)
if cels < -273 then
return nil
end
cels * 9 / 5 + 32
end
for i in 1..100 do
puts "摂氏#{i}℃ = 華氏#{cels2fahr(i)}°F"
end
def dice
rand(6) + 1
end
10000.times do
puts dice
end
#encoding : Windows-31J
def dice
rand(6) + 1
end
sum = 0
10.times do |i|
print "#{i + 1}回目:", j = dice, "¥n"
sum += j
end
puts "¥n合計:#{sum}"
def prime?(num)
if num == 2 then
return true
end
if num == 1 || num % 2 == 0 then
return false
end
i = 3
while(i < num) do
return false if num % i == 0
i += 2
end
return true
end
num = STDIN.gets.chomp.to_i
puts prime? num
targetDir = 'C:\from'
destDir = 'C:/to/'
checkFile = 'C:/hoge' + Time.now.strftime("%Y%m%d%H%M%S") + '.tmp'
Dir.chdir(targetDir)
File.open(checkFile, 'w') {|file|}
while(true) do
break if !File.exists?(checkFile)
Dir.glob('*') do |file|
puts file
File.rename(file, destDir + file)
end
sleep 7
end
src = 'C:/src'
dest = 'C:/dest'
mv = Proc.new do |file|
dest_file = dest + file
if File.exist?(dest_file) then
dest_file = dest_file + '_' + Time.now.strftime('%Y%m%d%H%M%S') + File.extname(dest_file)
end
puts dest_file
File.rename(file, dest_file)
end
Dir.chdir(src)
loop do
Dir.glob('*') do |file|
mv.call(file) if 300 < Time.now - File.mtime(file)
end
sleep 1800
end
targetDir = 'C:\hoge'
Dir.chdir(targetDir)
loop do
Dir.glob('*') do |file|
if 600 <= Time.now - File.stat(file).mtime then
puts "Delete : #{file}"
begin
File.delete(file)
rescue => e
# 削除失敗しても特に問題ではないのでメッセージだけ出して続行
$stderr.puts e
end
end
end
sleep 60
end
#encoding: Windows-31J
puts 'aaa'.upcase
class String
def upcase
'でっていう'
end
end
puts 'aaa'.upcase
require 'open-uri'
open('https://www.ruby-lang.org/ja/') do |f|
print f.read
end
class Point
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def +(other)
self.class.new(@x + other.x, @y + other.y)
end
def -(other)
self.class.new(@x - other.x, @y - other.y)
end
def inspect
"(#{@x}, #{@y})"
end
end
p1 = Point.new(10, 5)
p2 = Point.new(3, 4)
p p1 + p2
p p1 - p2
$stdout.puts 'output to stdout'
$stderr.puts 'output to stderr'
File.open("test.txt", "w") do |file|
file.puts("あああああああああ")
end
class Super
def hello
return "super"
end
end
class Sub < Super
def hello
return "sub"
end
end
c = Sub.new
puts c.hello
def few_param(a: 'a', b: 'b', c: 'c')
p a
p b
p c
end
few_param(a: 'aaa', b: 'bbb', c: 'ccc')
# few_param('111', '222', '333')
few_param(a: 'AAA')
few_param
array = ["君が", "泣くまで", "殴るのをやめない"];
array.each do |i|
puts i + "ッッッ"
end
def password_gen(size=8)
[*0..9, *'a'..'z', *'A'..'Z'].sample(size).join
end
puts 10.times.map { password_gen }
# 自分の得意な言語で
# Let's チャレンジ!!
# 区間数, コマの個数
t, n = gets.split.map {|i| i.to_i}
m_list = []
n.times do |i|
m_list << gets.chomp.to_i
end
# 区間の始まりのインデックス
index = 0
# 合計値の配列
sum_list = []
begin
# 区間数の配列
sub_list = m_list[index, t]
sum_list << sub_list.inject(:+)
index += 1
end until sub_list.empty?
puts sum_list.compact.max
# 自分の得意な言語で
# Let's チャレンジ!!
# 区間数, コマの個数
t, n = gets.split.map {|i| i.to_i}
m_list = []
n.times do |i|
m_list << gets.chomp.to_i
end
# 累積和
cumlative_sum = []
sum = 0
m_list.each do |i|
sum += i
cumlative_sum << sum
end
# 配列の最後の開始位置
last = m_list.size - t
# 最大値を探す
max = 0
(0..last).each do |i|
answer = cumlative_sum[i + t - 1] - cumlative_sum[i - 1]
max = [max, answer].max
end
max = m_list[0] if t == 1
puts max
input = STDIN.gets.chomp
File.open(input, "w") do |file|
file.puts "use strict;"
file.puts "use warnings;\n"
end
#encoding: UTF-8
require 'pg'
begin
conn = PGconn.connect('localhost',5432,'','','','postgres','postgres')
q = "delete from zip_code_data"
conn.exec(q)
rescue => ex
File.open('error.log', 'w') do |file|
file.print(ex.class," -> ",ex.message)
end
ensure
conn.close if conn
end
#encoding: UTF-8
require 'pg'
begin
conn = PGconn.connect('localhost',5432,'','','','postgres','postgres')
conn.transaction do |conn2|
File.foreach('input.txt', :encoding => Encoding::UTF_8) do |line|
conn2.exec_params('insert into zip_code_data values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)', line.chomp.split(','))
end
end
rescue => ex
$stderr.puts ex.message
ensure
conn.close if conn
end
#encoding: UTF-8
require 'pg'
begin
conn = PGconn.connect('localhost',5432,'','','','postgres','postgres')
q = "select * from zip_code_data"
res = conn.exec(q)
File.open('result.txt', 'w') do |file|
file.puts res[0].keys.join(',')
res.each do |r|
file.puts r.values.join(',')
end
end
rescue => ex
File.open('error.log', 'w') do |file|
file.print(ex.class," -> ",ex.message)
end
ensure
conn.close if conn
end
class A
def method
puts "method in A"
end
end
class B
def method
puts "method in B"
end
end
class C
def method
puts "method in C"
end
end
def getInstance
flg = rand(3)
case flg
when 0 then
return A.new
when 1 then
return B.new
when 2 then
return C.new
end
end
obj = getInstance
obj.method
def prime?(num)
return true if num == 2
return false if num.even? or num == 1
3.step(num, 2) do |i|
break if num == i
return false if num % i == 0
end
true
end
(1..100).each do |i|
puts i if prime?(i)
end
class TestClass
private
def private_method
puts 'called'
end
end
t = TestClass.new
#t.private_method
t.send(:private_method)
#encoding : Windows-31J
block = Proc.new { puts "called" }
puts "この次に実行されます" #この次に実行されます
block.call #called
pid = spawn 'sleep 5; echo terminated'
puts 'waiting...'
Process.waitpid(pid)
IO.popen('ping -c 10 localhost', 'r') do |pipe|
while line = pipe.gets
line.match(/time=(\d.\d+) ms/)
puts line if $1.to_f < 0.1
end
end
#!/usr/bin/env ruby
class Point
attr_accessor :x, :y
protected :x=, :y=
def initialize(x = 0, y = 0)
@x = x
@y = y
end
def swap(other)
tmp_x, tmp_y = @x, @y
@x, @y = other.x, other.y
other.x, other.y = tmp_x, tmp_y
self
end
def to_s
"x = #{@x}, y = #{@y}"
end
end
p1 = Point.new
p2 = Point.new(2, 3)
puts p1
puts p2
p1.swap(p2)
puts p1
puts p2
p1.x = 100
object = Object.new
dog = object.clone
def dog.sit
puts 'I\'m sitting.'
end
dog.sit
myDog = dog.clone
myDog.sit
puts "hello world!"
class Queue
def initialize
@array = Array.new
@length = 0
end
def enqueue(arg)
@array[@length] = arg
@length += 1
end
def dequeue
if @length == 0 then
return nil
end
value = @array[0]
i = 1
while i < @length do
@array[i - 1] = @array[i]
i += 1
end
@length -= 1
return value
end
end
queue = Queue.new
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
p queue.dequeue
p queue.dequeue
p queue.dequeue
p queue.dequeue
print "hello!\n"
print 'hello!\n'
print "3桁:"
threeNumber = rand(10).to_s +
rand(10).to_s +
rand(10).to_s
puts threeNumber
print "4桁:"
fourNumber = rand(10).to_s +
rand(10).to_s +
rand(10).to_s +
rand(10).to_s
puts fourNumber
start_time = Time.now
File.open('result.txt', 'w') do |wf|
File.foreach('input.txt') do |line|
wf.print line
end
end
end_time = Time.now
puts end_time - start_time
Dir.chdir('c:\$Recycle.Bin\S-1-5-21-448304718-1368734688-3449716590-1001')
puts Dir.glob('*').size
print '整数を入力してください >'
input = $stdin.gets.to_s.chomp.encode(Encoding::UTF_8)
print "#{input}は"
if input =~ /^[+-]?\d+$/ then
puts "整数です。"
else
puts "整数ではありません。"
end
address = "[email protected]"
/(^.*)@(.*\..*$)/ =~ address
p $1
p $2
puts "正規表現は難しい! なんて難しいんだ!".gsub(/難しいんだ/, "簡単なんだ").gsub(/難しい/, "簡単だ")
def word_capitalize(param)
return nil if !param.index("-")
words = param.split("-")
result = ""
words.each do |word|
result += word.capitalize + "-"
end
result[-1] = ""
return result
end
puts word_capitalize("in-replay-to")
puts word_capitalize("X-MAILER")
input = STDIN.gets.chomp
if /^-?\d+$/ =~ input then
puts "入力値は数字です。"
else
puts "入力値は数字ではありません。"
end
#encoding: Windows-31J
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
File.foreach(filename) do |line|
if pattern =~ line then
puts line
end
end
src = '/foo/*'
dest = '/tmp/'
Dir.glob(src) do |i|
name = File.basename(i)
dest_name = "#{dest}#{name}"
while File.exists?(dest_name) do
name += Time.now.strftime("%Y%m%d%H%M%S%N") + File.extname(name)
dest_name = "#{dest}#{name}"
end
puts dest_name
File.rename(i, dest_name)
end
print "読み込むファイル名>"
filename = STDIN.gets.chomp.encode("UTF-8")
print "置換前の文字列>"
from = STDIN.gets.chomp.encode("UTF-8")
print "置換後の文字列>"
to = STDIN.gets.chomp.encode("UTF-8")
fileContent = File.read(filename, :encoding => Encoding::UTF_8)
fileContent = fileContent.gsub(/#{from}/, to)
File.open("result.txt", "w") do |file|
file.puts(fileContent)
end
i = Integer("2") rescue 0
p i
i = Integer("a") rescue 0
p i
begin
i = Integer('a')
rescue => e
$stderr.puts e
end
range = 'a'..'z'
range.reverse_each do |c|
puts c
end
files = Dir.glob('/tmp/*')
.select {|file| File.size(file) < 9000 }
files.each do |file|
puts file
File.delete(file)
end
#encoding: Windows-31J
Dir.chdir('C:\img\tmp')
Dir.glob('*') do |item|
line = nil
File.open(item, 'r') do |file|
line = file.gets
end
if line.include?('html') then
puts item
File.rename(item, "C:/hoge/#{item}")
end
end
#encoding : Windows-31J
def rmdirs(start)
Dir.chdir(start)
files = Dir.glob("*")
puts files.size
files.each do |i|
puts i
if FileTest.directory?(i)
puts Dir.pwd + "/" + i
rmdirs(Dir.pwd + "/" + i)
end
end
Dir.chdir("..")
Dir.rmdir(start)
end
rmdirs('C:¥foo¥bar')
lvar = "toplevel"
#puts lvar
class C
lvar = "in class"
# puts lvar
def method
lvar = "in method"
puts lvar
end
end
module M
lvar = "in module"
end
#C.new.method
require 'socket'
# 待ち受けるポートを指定
s = TCPServer.new(12345)
loop do
cl = s.accept
cl.print Time.now.strftime('%c')
cl.close
end
class C
def value
return @value
end
def value=(arg)
@value = arg
end
end
obj = C.new
obj.value = "luigi mansion"
puts obj.value
#!/usr/bin/env ruby
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
File.foreach(filename) do |line|
if pattern =~ line then
puts line
end
end
require 'singleton'
class MyCount
include Singleton
def up
@count += 1
end
def initialize
@count = 0
end
end
a = MyCount.instance
b = MyCount.instance
puts a.up
puts b.up
c = MyCount.new
puts c.up
a = []
10000000.times do
a << rand
end
puts Time.now
a.sort_by {|x, y| x.to_f <=> y.to_f}
puts Time.now
ary = %w(
Ruby is a open source programming language with a focus
on simplicity and productivity. It has an elegant syntax
that is natural to read and easy to write
)
call_count = 0
sorted = ary.sort do |a, b|
call_count += 1
a.size <=> b.size
end
puts "sorted : #{sorted}"
puts "size : #{ary.size}"
puts "count : #{call_count}"
content = File.read "test.txt"
array = content.split "ttp://"
array.each do |item|
puts "http://" + item
end
class Stack
def initialize
@array = Array.new
@length = 0
end
def push(arg)
@array[@length] = arg
@length += 1
end
def pop
if @length == 0 then
return nil
end
value = @array[@length - 1]
@array[@length - 1] = nil
@length -= 1
return value
end
end
stack = Stack.new
stack.push(1)
stack.push(2)
stack.push(3)
puts stack.pop
puts stack.pop
puts stack.pop
p stack.pop
class C
@@value = "test"
def self.setValue(arg)
@@value = arg
end
def self.getValue
return @@value
end
def C.printValue
print @@value
end
end
C.printValue
puts
C.setValue("wario")
puts C.getValue
str = "detteiu"
puts str[0]
puts str[2, 3]
puts str[2..4]
puts str[100] == nil
ar = "Ruby is an object oriented programming language".split(" ")
p ar
str = "detteiu"
str[7] = "!"
puts str
str[0, 2] = "***"
puts str
def str2hash(str)
tokens = str.split(/\s+/)
def tokens.xvalues_at(method)
to = self.size - 1
self.values_at(*(0..to).select{|i| i.send(method)})
end
t1 = tokens.xvalues_at(:even?)
t2 = tokens.xvalues_at(:odd?)
t1.zip(t2).to_h
end
str = "スリジャヤワルダナプラコッテ"
puts str.reverse
puts str
puts str.reverse!
puts str
# 自分の得意な言語で
# Let's チャレンジ!!
a, b = gets.split.map{|i| i.chomp}
s = gets.chomp
loop do
a_index = s.index(a)
break unless a_index
b_index = s.index(b, a_index + a.length)
break unless b_index
answer = s[(a_index + a.length)..(b_index - 1)]
answer = '<blank>' if answer.empty?
puts answer
s.slice!(0, b_index + b.length)
end
start = Time.now
str = ''
100000.times do
str += 'abc'
end
finish = Time.now
puts "#{finish - start}秒"
puts str.length
start = Time.now
str = ''
100000.times do
str << 'abc'
end
finish = Time.now
puts "#{finish - start}秒"
puts str.length
ar = "Ruby is an object oriented programming language".split(" ")
ar.sort!
p ar
ar = "Ruby is an object oriented programming language".split(" ")
ar.sort! do |a, b|
a.downcase <=> b.downcase
end
p ar
ar = "Ruby is an object oriented programming language".split
str = ""
ar.each do |item|
str += item.capitalize + " "
end
str[(str.size - 1)] = ""
p str
str = "Ruby is an object oriented programming language"
charHash = {}
str.each_char do |char|
if charHash.key?(char) then
charHash[char] += 1
else
charHash[char] = 1
end
end
charHash.each do |char, count|
print "\'#{char}\': "
count.times do
print "*"
end
puts
end
def kan2num(kan)
map = {
"一"=>"1",
"二"=>"2",
"三"=>"3",
"四"=>"4",
"五"=>"5",
"六"=>"6",
"七"=>"7",
"八"=>"8",
"九"=>"9",
"十"=>"十",
"百"=>"百",
"千"=>"千"
}
str = ""
kan.each_char do |char|
str += map.fetch(char, "")
end
#1000の位
if temp = (str.index("千")) then
thousand = str[temp - 1] rescue 1
end
end
puts kan2num("千五百三")
ary1 = [1, 2, 3]
ary2 = [10, 20, 30]
ary3 = [100, 200, 300]
result = []
(0..2).each do |i|
result << ary1[i] + ary2[i] + ary3[i]
end
p result
ary1 = [1, 2, 3]
ary2 = [10, 20, 30]
ary3 = [100, 200, 300]
result = []
ary1.zip(ary2, ary3) do |a, b, c|
result << a + b + c
end
p result
ary1 = [1, 2, 3]
ary2 = [10, 20, 30]
ary3 = [100, 200, 300]
result = []
ary1.zip(ary2, ary3) do |a|
result << a.inject(:+)
end
p result
class Test
def test_method
puts 'スーパークラスのメソッド'
end
end
class TestSub < Test
def test_method
super
puts 'サブクラスのメソッド'
end
end
t = TestSub.new
t.test_method
sym = :test
p sym
p sym.to_s
def tail(lineno, file)
lines = File.foreach(file).to_a
from = [lines.size, lineno].min
from = -from
lines[from..-1].each do |line|
puts line
end
end
print "aaa"
#encoding:Windows-31J
print "あなたの名前なんですか:"
name = STDIN.gets
name = name.chomp
puts "お名前は" + name + "さんですね。"
name = STDIN.gets.chomp
puts name
$stdout.sync = false
$stderr.sync = false
$stdout.print 'out1 '
$stderr.print 'err1 '
$stdout.print 'out2 '
$stdout.print 'out3 '
$stderr.print "err2\n"
$stdout.print "out4\n"
lunch = ["udon", "soba", 1]
puts lunch[0]
lunch[3] = "pasta"
puts lunch[3]
sanuki, shinshu = lunch
puts sanuki
puts shinshu
#encoding : Windows-31J
#クラス定義
class Udon
#コンストラクタ
#引数なしコンストラクタを呼んだ場合もここが呼ばれ、デフォルト引数が適用される
def initialize(mytype="かけ")
#@付き変数はインスタンス変数
@type = mytype
end
# def type
# return @type
# end
def type= (menu)
@type = menu
end
def order
puts "#{@type}うどん"
end
end
#継承
class UdonSub < Udon
end
#インスタンス化
normal = UdonSub.new
normal.order
sanuki = UdonSub.new("讃岐")
sanuki.order
tanuki = UdonSub.new("たぬき")
tanuki.order
#tanuki.type("きつね") ←エラー
tanuki.type = "きつね"
tanuki.order
#エンコード指定なし日本語コメント
print "hello"
require 'csv'
csv = CSV.read('./home6.csv')
csv.each do |i|
puts i.class.name
end
# encoding: Windows-31J
i = 124
if i == 123
print "iは123です"
elsif i == 124
print "iは124です"
else
print "iは不明な値です"
end
lunch = ["udon", "soba", "pasta"]
lunch.each{ | i |
puts i
}
lunch = {"udon" => "sanuki", "soba" => "shinshu"}
puts lunch["udon"]
puts lunch["soba"]
lunch = {"udon" => "sanuki", "soba" => "shinshu", "pasta" => "italian"}
lunch.each_key { | i |
puts i + "\t: " + lunch[i]
}
#encoding:Windows-31J
input = STDIN.gets
#if /^-?\d+$/ =~ input どちらでもよい
if input =~ /^-?\d+$/
print "入力値は数値です"
else
print "入力値は数値ではありません"
end
#encoding : Windows-31J
i = "i"
u = "u"
def i.love(other)
print "i love #{other}"
end
i.love(u)
#u.love(u)←i love utestTokui.rb:12:in `<main>': undefined method `love' for "u":String (NoMethodError)
names = %w(alice white-rabbit cheshire-cat)
threads = []
names.each do |name|
threads << Thread.new do
3.times do |i|
print "#{name}:#{i}, "
end
end
end
threads.each {|t| t.join}
puts "\nall threads are terminated."
require 'io/console'
# 1秒おきに時刻を表示するスレッド
view_thread = Thread.new do
loop do
print "\033[2K\r#{Time.now.strftime('%F %T')}"
sleep 1
end
end
# 入力待ちスレッド
input_thread = Thread.new do
while STDIN.getch != 'q'
end
puts
view_thread.kill
end
view_thread.join
input_thread.join
puts Time.now
puts Time.mktime(2112, 9, 3)
now = Time.now.to_a
now.each do |item|
puts item
end
i = 10
i.times do
puts "detteiu"
end
100.times do |i|
print i + 1, "番目のループ\n"
end
a = 10.times.map {'でっていうwww'}
puts a
puts a.class.name
puts 123.to_s().class.name
a = 'でっていう'
class String
def to_w
self + 'www'
end
end
puts a.to_w
a = 'でっていう'
b = a.clone
def a.to_w
self + 'www'
end
puts a.to_w
puts b.to_w
require "CSV"
array = ["あああ", "いいい", "ううう"]
puts array.to_csv
def total(from, to)
sum = 0
from.upto(to) do |num|
if block_given? then
sum += yield(num)
else
sum += num
end
end
sum
end
puts total(1, 10)
puts total(1, 10) {|num| num ** 2}
def total(from, to, &block)
sum = 0
from.upto(to) do |num|
if block then
sum += block.call(num)
else
sum += num
end
end
sum
end
puts total(1, 10)
puts total(1, 10) {|num| num ** 2}
if $stdout.tty?
$stderr.puts 'stdout is tty.'
else
$stderr.puts 'stdout is not tty.'
end
# グループクラス
class Group
attr_reader :count, :seat_nums
def initialize(a_i, b_i)
# グループの人数
@count = a_i
# 座ろうとする座席番号
@seat_nums = []
@count.times do |i|
@seat_nums << b_i + i
end
end
def to_s
"@count = #{@count}, @seat_nums = #{@seat_nums.to_s}"
end
end
# グループ数と座席数
n, m = gets.split.map {|i| i.to_i}
# 人数と座る座席
groups = []
m.times do
a_i, b_i = gets.split.map {|i| i.to_i}
groups << Group.new(a_i, b_i)
end
# 座席
seat = Hash.new
array = (1..n).to_a
array.each do |i|
seat[i] = false
end
groups.each do |group|
# 前の座席
seat_bf = seat.clone
group.seat_nums.each do |seat_num|
unless seat[seat_num]
seat[seat_num] = true
else
seat = seat_bf
break
end
end
end
puts seat.select {|k, v| v}.size
#encoding: UTF-8
puts "\u6587"
s = '\\' + 'u6587'
puts s[2, 4].hex.chr('UTF-8')
i = 10
j = 20
unless i < j then
puts "iはjより大きい"
else
puts "iはjより小さい"
end
require "open-uri"
open("http://www.google.co.jp/") do |uri|
File.open("result.html", "w") do |html|
html.puts(uri.read)
end
end
require 'open-uri'
File.foreach('dats.txt') do |dat|
open(dat) do |uri|
File.open('result.txt', 'a') do |file|
file.puts(uri.read)
end
end
end
#encoding : Windows-31J
require "./lib"
grep "test.txt", "あ"
puts "日本語"
class UnacceptableRequiredError < StandardError
# attr_reader :obj
#
# def initialize(obj)
# @obj = obj
# end
end
class Vessel
def pour_out
requid = @requid
@requid = nil
requid
end
def pour_in(requid)
if requid.to_s == acceptance then
@requid = requid
else
raise UnacceptableRequiredError.new(requid), 'unacceptable'
end
end
def acceptance
raise NotImplementedError.new, '#acceptance is not implemented!'
end
end
class Teapot < Vessel
def initialize(requid)
pour_in(requid)
end
def acceptance
'tea'
end
end
#encoding: Windows-31J
array = %w{ RXキック リボルケイン ボルティックシューター バイオブレード }
array.each do |skill|
puts skill
end
#encoding : Windows-31J
require './windlg'
# ダイアログ
d = WinDlgt.new("Windows-31J")
# ダイアログのメタデータ
ofn = OPENFILENAME.new
ofn.sTitle = "ファイルを開く"
ofn.sArFilter = [[ "テキスト(*.txt)", "*.txt"], ["すべて(*.*)", "*.*"] ]
ofn.iFilterIndx = 0
ofn.sIniDir = ENV["USERPROFILE"] + '¥Documents'
ofn.iFlags = OFN_FILEMUSTEXIST
#d.msgbox("テスト", "title", MB_YESNOCANCEL)
#s = d.inputBox("入力", "title")
#puts s
if d.getOpenFileName(ofn) != 0 then
puts ofn.sFnameFull
puts ofn.sFname
end
exit unless ARGV[0]
count = Hash.new(0)
File.foreach(ARGV[0]) do |line|
line.chomp!
words = line.split
words.each do |w|
count[w] += 1
end
end
count = count.sort do |a, b|
a[1] <=> b[1]
end
count.each do |key, val|
puts "#{key} : #{val}"
end
require "CSV"
CSV.open("result.csv", "w") do |csv|
csv.puts ["クロム", "ロード", "封剣ファルシオン"]
csv.puts ["ルフレ", "戦術師", "サンダー"]
csv.puts ["フレデ肉", "グレートナイト", "銀の槍"]
end
input = File.read("tests.txt", :encoding => Encoding::UTF_8)
File.open("result.txt", "w") do |file|
i = 0
while i < 5 do
file.puts(input)
i += 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment