0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

count及びmapの使い方 特定の値を数える。 

Last updated at Posted at 2019-03-05

下のように「a」が6つ「nil」が4つ文字列があった時
3番目から9番目(m[2..8])にaがいくつあるか。

m = [ "a" , "a" , "a" , "a" , "a" , "a" , nil , nil , nil, nil ]
m[2..8].count("a") => 4

文字列の中に文字列がある場合は

m = [[ "a" , "a" , "a" , "a" , "a" , "a" , nil , nil , nil , nil ],
     [ nil , nil , nil , nil , "a" , "a" , "a" , "a" , "a" , "a" ]]
# 上段
m[0][2..8].count("a") => 4
# 下段
m[1][2..8].count("a") => 5

*縦に調べたい場合、同じようにすると間違います。(失敗例)

(m[0][0]とm[0][1]でaの数を調べる)

# 左から1番目の列
m[0..1][0].count("a") => 6

同じようにするとなぜか6になります。(上段のaの数になる)
*理由を知っている方がいたら教えてください。

mapを使って一段ずつ呼び出して、今回は一番左の列の情報が欲しいので、i[0]としています。

m.map{|i|i[0]}.count("a") => 1

配列の中に条件(i > 4)に当てはまった数を返す。

a=[1,2,3,4,5]
a.count{|i|i > 4} => 1

もっと良い方法があったり、こういう考え方もあると思った人はコメントしていただけると助かります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?