ちくわ工務店

雰囲気でつくろう

書き方メモ Ruby

Ruby初心者なのでggr方もよちよちである。

同じ苦労の繰り返しはつらいので随時まとめる。

continue的なやつ

nextを使う

map

概要

配列の中身を変換する

用例

a1 = [100, 200, 300]
a2 = a1.map { |x| x * 2 }
p a2 # => [200, 400, 600]

参考

Rubyのmap, map!メソッドの使い方 - UX MILK

reduce

概要

配列の内容を使って繰り返し計算する

用例

numbers = [1,2,3,4,5]
puts numbers.reduce {|sum, n| sum + n } # => 15

参考

https://ref.xaio.jp/ruby/classes/enumerable/reduce

オブジェクトの変換

StringInteger

用例

s = "1993"
puts s.to_i # => 1993

参考

https://ref.xaio.jp/ruby/classes/string/to_i

Addressable::URIString

用例

Addressable::URI.encode(url)

参考

http://www.rubydoc.info/gems/addressable/Addressable/URI#encode-class_method

文字列操作

連結

str = 'abc' << 'def'
# => "abcdef"
str = 'abc'.concat('def')
# => "abcdef"

参考

https://qiita.com/Kta-M/items/c7c2fb0b61b11d3a2c48