Skip to content

Instantly share code, notes, and snippets.

@sadah
Created November 25, 2012 11:44
Show Gist options
  • Save sadah/4143205 to your computer and use it in GitHub Desktop.
Save sadah/4143205 to your computer and use it in GitHub Desktop.
Ruby Tips
<%- # 空行が表示されない(rails) -%>
<% # 空行が表示される(rails) %>
# こんな感じのコードが
ary = (1..100).to_a
while ary.size != 0
p ary.slice!(0,15)
end
# こんな感じに書ける。
(1..100).to_a.each_slice(15){|a| p a}
# JSONをいい感じにインデントして出力
require 'json'
puts JSON.pretty_generate({:a => "json", :b => [1,2,3], :c => { :d => 1, :e => "eee"}})
# =>
# {
# "a": "json",
# "b": [
# 1,
# 2,
# 3
# ],
# "c": {
# "d": 1,
# "e": "eee"
# }
#}
#Userがあって、nameを持っているとする
class User
attr_accessor :name
end
u1 = User.new
u1.name = "u1"
u2 = User.new
u2.name = "u2"
u3 = User.new
u3.name = "u3"
users = [u1,u2,u3]
# メソッド呼び出しの結果を配列にいれて返却してくれる
users.map(&:name)
# => ["u1", "u2", "u3"]
# users.map(&:name) は
# users.map{|user| user.name } のシンタックスシュガー
# 配列から最小値を取得
[1,2,3].min
# => 1
# 配列から最大値を取得
[1,2,3].max
# => 3
# 二つの変数の最大値を取得するとき、三項演算子を使ったりするけど
a,b = 1,2
a > b ? a : b
# これでオーケー
[a,b].max
nil.nil?
# => true
nil.try(:nil?)
# => nil
# id や timestamp のないテーブル (rails)
class CreateBars < ActiveRecord::Migration
def self.up
create_table :bars, :id => false do |t|
t.integer :bar
end
end
def self.down
drop_table :bars
end
end
# 配列からランダムに値を取得
[1,2,3,4,5].sample
# 配列からランダムに値を3つ取得
[1,2,3,4,5].sample(3)
# tryを使うとnilのエラーが起きない(rails)
# やりたいのは ary.max
ary = [1,2,3]
ary.try(:max)
# => 3
# aryがnilなのでエラー
ary = nil
ary.max
# => NoMethodError: undefined method `max' for nil:NilClass
# tryを使うとaryがnilならnilが返ってくる!
ary = nil
ary.try(:max)
# => nil
# tryの引数に渡すのはメソッドのシンボルなので、これはエラーになる。
hash = {:a => 1}
hash.try(:a)
# => NoMethodError: undefined method `a' for {:a=>1}:Hash
# 複数行処理できるメソッドがクラスメソッドにある。update_all とか。(rails)
User.update_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment