LoginSignup
1
1

More than 3 years have passed since last update.

# よく使うRubyのメソッドとハッシュの書き方

Last updated at Posted at 2019-04-16

scanメソッド(正規表現にマッチした文字列を配列にして返す)

def ints(arra)
  arr(/\w\w/).map do |s|
    s.hex
  end
end

もしくは、こうも書ける↓↓

map/collectメソッド(事前に空の配列を用意し、他の配列をループ処理した結果を空の配列に入れて、配列を返す)

def ints(array)
  arr(/\w\w/).map(&:hex)
  end
end

&に書く文字列の要素が入り、その要素毎にhexメソッドを適用させ、mapで、配列として返している。

違う書き方↓↓

array.map {|s|  s.hex }  

inject/reduceメソッド(配列を対象に、各要素毎に処理をした結果を繋げて、文字列を返す)

def to_hex(r,g,b)
  [r,g,b].inject('#') do |hex, n|
    hex + n.to_s(16).rjust(2, '0')
  end
end

where句の発展的な使い方(指定したフィールド内の値以外のレコードを取得したい場合)

def map
    # @pictures = Picture.all.where('not latitude is null and not longitude is null')
    # @pictures = Picture.all.where.not(latitude: nil).where.not(longitude: nil)
    @pictures = Picture.all.where.not("latitude = ?", "nil").where.not("longitude = ?", "nil")
    @api_key = ENV["GOOGLE_MAP_API"]
  end

ちょっと高度なハッシュ記法

# fromはキーmのこと。toはキーmのこと。

def convert_length(length, from: :i, to: :i)
  units = {m: 1.0, ft: 3.28, in: 39.37}
  (length / units[from]) * units[to].round(2) 
end

puts convert_length(15, from: :in, to: :m)
=> 0.38

ハッシュ

以下は同じ結果がでる。

products = {lemon: 145, aplle: 180, orange: 170, tomato: 120, grape: 140}
p products.delete_if{|key, value| key == :lemon || key == :tomato || key == :grape}
p products.select { |key, value| key > 160}
1
1
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
1
1