1
1

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 CGIプログラムを条件分岐で実行させる方法

Last updated at Posted at 2020-05-06

Rubyで作ったプログラムをWebプログラムとして動作させる方法を書いていきます。

CGIとは

Webサーバーと連携してプログラムを動作させる仕組みです。
ブラウザからWebサイトへアクセスがあった場合、CGIプログラムでは、コンテンツを動的に変化させて表示させることができます。

RubyのCGIで条件分岐

ある変数の状態で真か偽かを判定し、条件に合わせた処理を実行させます。Rubyでは、if (elsif) else でそれぞれの条件に合わせた処理をコーディングします。


if cgi.has_key?('dog')# フォームに 'dog' という変数(ハッシュ)があるときに真
  cgi.out("type" => "text/html", "charset" => "UTF-8") {
  # 情報の目印とした"dog"のデータを cgi['dog']と言う記述で取り出し、ローカル変数に代入する
    get = cgi['goya']
    # HTMLでレスポンスを返却する
      "<html>
        <body>
          <p>あいうえお</p>
          文字列:#{get}
        </body>
      </html>"
  }
elsif cgi.has_key?('dog1')
  cgi.out("type" => "text/html", "charset" => "UTF-8") {
    get = cgi['dog1']
      "<html>
        <body>
          <p>かきくけこ</p>
          文字列:#{get}
        </body>
      </html>"
  }
elsif cgi.has_key?('dog2')
  cgi.out("type" => "text/html", "charset" => "UTF-8") {
    get = cgi['dog2']
      "<html>
        <body>
          <p>さしすせそ</p>
          文字列:#{get}
        </body>
      </html>"
  }
end

key?メソッドで変数(ハッシュ)の中にキーがあるかを判定し、あった場合にif以下のブロック内の処理を実行します。
else以下のブロックは処理されないため、表示されません。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?