Created
July 25, 2012 12:29
-
-
Save shikakun/3175920 to your computer and use it in GitHub Desktop.
gist童貞卒業です
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = [1,2,3,4,5] | |
words = ['paperboy', 'lolipop', 'muumuu-domain', '30days album', 'sqale', 'osaipo', 'heteml'] | |
# 1. 配列の各要素を二倍した配列を返す | |
a.collect{|i|i*2} | |
# 2. 配列の要素をすべて足し算した結果を返す | |
b = 0 | |
a.each do |i| | |
b = b + i | |
end | |
p b | |
# 3. 要素に連番を振る | |
c = 0 | |
a.each do |i| | |
p c.to_s << ': ' << i | |
c = c + 1 | |
end | |
# 4. 偶数の要素だけ返す | |
d = [] | |
a.each do |i| | |
d << i if i % 2 == 0 | |
end | |
p d | |
# 5. nil 以外の要素だけを返す (最低二通りの解を考えてみよう) | |
# a = [1, nil, 2, 3, nil, 4, 5] | |
e = [] | |
a.each do |i| | |
e << i if i.kind_of?(Fixnum) | |
end | |
p e | |
# 6. 最初の偶数を返す (Array#[], Array#at などは禁止) | |
a.each do |i| | |
if i % 2 == 0 | |
p i | |
break | |
end | |
end | |
# 7. e を含む単語だけ返す | |
f = [] | |
words.each do |i| | |
f << i if i.include?('e') | |
end | |
p f | |
# 8. 配列の要素をすべて足し算した結果を返す (each 禁止) | |
g = 0 | |
h = 0 | |
a.length.times do | |
g = g + a[h] | |
h = h + 1 | |
end | |
p g | |
# 9. 要素に連番を振る (二回目) | |
j = 0 | |
words.length.times do | |
p j.to_s << ': ' << words[j] | |
j = j + 1 | |
end | |
# 応用形 | |
# 1. 整形されたマークダウンを出力する | |
# words = ["perl", "ruby", "python", "css", "js", "html", "c", "c++", "java" ] | |
k = 0 | |
words.each do |i| | |
if k % 3 == 0 | |
p '' | |
p '--' | |
end | |
k = k + 1 | |
p ' ' << k.to_s << '. ' << i | |
end | |
# 2. 3で割り切れるものだけを足す | |
# a = (1..30).to_a | |
l = 0 | |
a.each do |i| | |
l = l + i if i % 3 == 0 | |
end | |
p l |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment