Skip to content

Instantly share code, notes, and snippets.

#!/usr/local/env ruby
# -*- coding: UTF-8 -*-
# -*- coding: EUC-JP -*- #=> このmagic commentは無効
p "test".encoding #=> #<Encoding:UT-8>
# Magic Commentは1行目、もしくはshebangが1行目の場合は2行目の場合有効。
# Magic Commentが無い場合、US-ASCIIと判断される。
# Magic Commentの形式
# # coding: UTF-8
# coding: UTF-8
str_utf = "hoge"
str_euc = "hoge".encode("EUC-JP")
# ASCII互換コーディングをもつ7bitクリーンな文字列は
# エンコーディングに関わらずASCIIとして扱える
p str_utf == str_euc #=> true
p /hoge/ =~ str_utf #=> 0
# DuckTypingの単純な例
# ここで重要なのはSTDOUT(IOクラス)と
# StringIOクラスには継承関係がないとうこと。
#
require 'stringio'
def message_write(out, message)
out.write(message)
end
# coding: UTF-8
class Duck; end
def foo(obj)
raise TypeError, "アヒルじゃないです" unless obj.is_a? Duck
end
foo(Object.new) #=> TypeError
# coding: UTF-8
class Logger
def self.write(out, log)
out.write log
end
end
File.open("hoge", "w") do |f|
Logger.write(f, "log") # ファイルに書き込み
# coding: UTF-8
class Logger
def self.write(out, log)
raise TypeError, "書き込めない何かだよ" unless out.respond_to? :write
out.write log
end
end
File.open("hoge", "w") do |f|
# coding: UTF-8
class Logger
def self.write(out, log)
out.write log
rescue
raise TypeError, "書き込めない何かだよ"
end
end
# coding: utf-8
def profile(msg, &block)
start_time = Time.now
yield
duration = Time.now - start_time
puts msg << ": " << duration.to_s << "秒"
end
# coding: UTF-8
def counter_closer
count = 0
lambda{|n| count += n}
end
counter = counter_closer
puts counter.call(1)
puts counter.call(2)
#
# Railsで確認画面を実装するときのテンプレ
#
def confirm
if request.post?
@entry = Entry.new(params[:entry])
else request.put?
@entry = Entry.find(params[:id])
@entry.attributes = params[:entry]