5
5

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.

rubyの配列操作をmapでやる!!

Last updated at Posted at 2017-08-17

入力を受け取って配列に入れる操作

  • まずはCでこのように順番に文字列を入れると逆順に返すプログラムがあったとするよ!
reverse.c実行結果
#include<stdio.h>
int main(void) {
  int i;
  char kongo[4][100];
  for(i=0; i<4; i++) {
    scanf("%s", kongo[i]);
  }
  for(i=3; i>=0; i--) {
    printf("%s\n", kongo[i]);
  }
}
実行結果
> kongo
> hie
> haruna
> kirisima
kirisima
haruna
hie
kongo

Cからrubyに来てすぐに思いつく方法

0から3までのeachをつくって回していくよ!すっきりしてるね!

reverse.rbの実行結果
kongo = Array.new

(0..3).each do |i|
  kongo[i] = gets
end

(0..3).each do |i|
  puts kongo[3-i]
end

rubyはループを回して1つずつ表示させる必要がないぞ

配列を逆順にしたいときはreverseメゾットを使う。2行省略できる!

reverse.rbの実行結果
kongo = Array.new

(0..3).each do |i|
  kongo[i] = gets
end

puts kongo.reverse

「本題」mapを使って配列を生成

これでさらに初期化もする必要がなくなって産業も省略できるぞ。やったね!

reverse.rbの実行結果
kongo = (0..3).map { gets }
puts kongo.reverse

もうさらには1行で表現できるぞ

C言語に戻れなくなるぅ

reverse.rbの実行結果
puts ((0..3).map { gets }).reverse

さらにきれいに

美しい!

reverse.rbの実行結果
puts 4.times.map{ gets }.reverse
5
5
8

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?