LoginSignup
4
4

More than 5 years have passed since last update.

Rubyメモ

Last updated at Posted at 2013-12-04

例外

begin
  User.find(param[:id])
rescue ActiveRecord::RecordNotFound => e
  p e
end

ディレクトリがなければ作る

path = "/home/take/diary"
Dir::mkdir(path, 0755) unless Dir.exist?(path)

常にtrueを返すオブジェクト

hoge = Class.new do
  def method_missing(*args)
    true
  end
end.new

p hoge.piyo # => true

ヒアドキュメント

class_eval <<-METHODS, __FILE__, __LINE__ + 1
  ....
METHODS

__FILE__, __LINE__ + 1 この部分なんだろ?

Hash to Struct

def hash_to_struct(hash)
  Struct.new(*hash.keys).new(*hash.values.map{|s| Hash === s ? hash_to_struct(s) : s})
end

json string => ruby object

JSON.parse()

ruby object => json string

JSON.generate()

file write

File.open(@options[:path], 'w') do |f|
  f.write JSON.generate(data)
end

file read

File.open(@options[:path]).read

file

File.dirname
File.exists?
Dir::mkdir

STDIN

STDIN.gets

STDOUT

puts # 改行あり
print # 改行なし
p
pp

catch 多重ブロックのbreak 大域脱出

resutl = catch(:hoge) do
  trhow :hoge, result
end

コストは安くない http://d.hatena.ne.jp/syonbori_tech/20111020/1319107721

find.rbによる例 http://d.hatena.ne.jp/yarb/20121012/p1

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4