コーディングテスト用のメモ。
基礎文法
繰り返し
- for
for i in 1..3 do
puts i
end
※配列でも可
for num in [1, 2, 3] do
puts num
end
- each
[1, 2, 3, 4].each do |num|
p num
end
- while
num = 0 #初期値
while num <= 12 do #条件
p num #処理
num += 3 #値の更新
end
- times
3.times do |num|
p num
end
各桁の和
a = 11
puts a.to_s.split('').map{|x| x.to_i}.inject(:+)
#=> 2
a = 11
puts a.to_s.chars.map{|x| x.to_i}.sum
### 奇数or偶数番目要素の取得
a = 11
puts a.digits.sum
条件分岐(書き換えパターン)
- pattern(1)
s = "hoge"
if s==hoge
puts "YES"
else
puts "NO"
end
#=>YES
- pattern(2)
s = "hoge"
puts s == hoge ? "YES":"NO"
#=>YES
- pattern(3)
s = "hoge"
case s
when "hoge" then
puts "YES"
when "no_hoge" then
puts "NO"
#=>YES
.gsub(パターンマッチング)
string = "ruby ruby ruby"
puts string.gsub(/ruby/, 'python')
#=> python python python
数値の切り捨て
1.4.floor # 1
1.5.floor # 1
-1.4.floor # -2
-1.5.floor # -2
数値の切り上げ
1.4.ceil # 2
1.5.ceil # 2
-1.4.ceil # -1
-1.5.ceil # -1
配列の操作
配列の割り算
a = [2, 4, 6]
b = a.map(|x| x/2)
puts b
#=> [1, 2, 3]
配列の合計
a = [1, 2, 3]
puts a.inject(:+)
#=> 6
ary = ('a'..'j').to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
# 偶数番目
ary.select.with_index { |_, i| i.even? }
#=> ["a", "c", "e", "g", "i"]
# 奇数番目
ary.select.with_index { |_, i| i.odd? }
#=> ["b", "d", "f", "h", "j"]
並べ替え
ary = [2, 4, 1, 5, 3]
# 昇順
ary.sort
#=> [1, 2, 3, 4, 5]
# 降順
ary.sort.reverse
#=> [5, 4, 3, 2, 1]
重複要素を統一
ary = [1, 2, 2, 3, 3]
ary.uniq
#=> [1, 2, 3]
配列→文字列
ary = [1, 2, 3, 4, 5]
ary.join(' ')
#=> '1 2 3 4 5'
要素の追加
ary = ['a', 'b', 'c']
ary << 'd'
#=> ['a', 'b', 'c', 'd']
最大値最小値
ary = [1, 25, 50, 75, 100]
ary.minmax
#=> [1, 100]