LoginSignup
0
0

Ruby芸160チャレンジ(#6)For文

Last updated at Posted at 2023-12-05

この記事は何

shellgei160を通じて言語習得 Advent Calendar 2023に参加しています。

書籍「シェル芸ワンライナー160本ノック」の例題をRubyで解いてみて、Rubyの学習に役立てようとするものです。

例題はこちらのリポジトリで公開されているものに限ります。
https://github.com/shellgei/shellgei160

実行環境など

  • Docker image: ruby:3.0.2
  • 上記リポジトリをクローンした上で、リポジトリのルートディレクトリ直下にanswer-rubyディレクトリを作り、その中に解答となるファイルを作成していきます。

今回のテーマ

$ seq 5 | awk '{for(i=1;i<$1;i++){printf " "};print "x"}' | tac

次のような文字列を表示する処理です。

    x
   x
  x
 x
x

for文で徐々にスペースを開けるようにしながら、最後にtacで上下を反転させています。

n_lines = 5
puts (1..n_lines).map { |i| "#{' ' * (i - 1)}x" }.reverse

所見

  • ワンライナー感ありますね!こういう処理を書くにはRuby完結で良き。
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