Skip to content

Instantly share code, notes, and snippets.

@semind
Created January 17, 2012 14:01
Show Gist options
  • Select an option

  • Save semind/1626711 to your computer and use it in GitHub Desktop.

Select an option

Save semind/1626711 to your computer and use it in GitHub Desktop.
rubyメモ
### 配列の中身を個々の変数に分割して代入
test = ['a', 'b', 'c']
test << 'd'
p test # => ["a", "b", "c", "d"]
### ファイルからの相対パスでライブラリを読み込むためのイディオム
# $:は$LOAD_PATHと等価
$:.unshift(File.dirname(__FILE__))
$:.unshift(File.dirname(__FILE__) + "/lib")
### 配列の中身を個々の変数に分割して代入
a,b,c = *[1,2,3]
a # => 1
b # => 2
c # => 3
### 文字列をsplitして最後の要素だけArrayから削除する
test = "a.b.c.d.e.f"
p test.split('.')[0..-2] # => ["a", "b", "c", "d", "e"]
### module内でのクラスメソッドとインスタンスメソッド
module SampleModule
# class method
def self.hello
puts "hello"
end
# instance method
def goodby
puts "goodby"
end
end
### ファイルからの相対パスでライブラリを読み込むためのイディオム
# $:は$LOAD_PATHと等価
$:.unshift(File.dirname(__FILE__))
$:.unshift(File.dirname(__FILE__) + "/lib")
### 文字列整形に%を使える
"%5d, %5s"%([num,string])
### ファイル出力時にバッファリングしない
f = File.open('output.txt', 'w')
f.sync = true
### 再帰的にディレクトリを作る場合はfileutilsを使うと良い
require 'fileutils'
FileUtils.mkdir_p(dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment