13
0

More than 3 years have passed since last update.

Rubyの基礎[1]

Last updated at Posted at 2020-12-02

rubyのStringsの表示

method 使用状況
print 普通に使う.要改行
puts 次に普通に使う. 自動改行
p codingの最中にdebugがわりに打ち出すとき
pp pのpretty print, require 'pp'が必要
printf cのがあります.formatを整えるときに便利

ect

文字列を囲む' 'と" "のわかりやすい違いは,
" "だと特殊文字の機能(改行\nみたいな)を使えるけど,' 'だと使えない.
他にも表示に違いがあるらしい.

ダブルクォーテーション

$ puts "改\n行"


シングルクォーテーション

$ puts '改\n行'
\n

hello_worldを表示する

Hello world.

と表示するプログラムから

解説

まずは,emacsでプログラムを書くファイルを開く,

$ emacs hello_world.rb                                               

表示したい文字列(Hello world.)を''で囲って,

puts 'hello world'

を書けたら,C-x,C-s(保存)してC-x,C-c(終了)

$ ruby puts_hello_world.rb

と打ち込み実行.

ARGV[0]を使う

お題

$ ruby hello_name.rb Rudy

と打ち込んだ時に,

Hello Rudy.

と返すプログラムを書いてみる.

簡単な解説

putsしたら普通はgetsだが,目的の一つであるshell環境ではcommand line interfaceで作業をするためにARGV[0]というのを使って行く.hello_name.rb に書き込む.

puts ARGV[0]

実行してみる.

$ ruby hello_name.rb Rudy
Ruby

Hello Rubyとするために

これらが方法としてあるらしい

puts puts "Hello " + ARGV[0]
puts puts "Hello #{ARGV[0]}"
print print "Hello #{ARGV[0]}\n"
print print "Hello " + ARGV[0] + "\n"

解説

hello_name.rb を書き換えて

puts "Hello #{ARGV[0]}"

実行してみる.

$ ruby hello_name.rb Rudy                                                   
Hello Ruby                                                                        

redirect

txtへ出力させる

ruby hello_name.rb Ruby > hello_name.txt

としてhello_name.txtに結果を出力させることができる.実行する度に内容は上書きされる.

'>'は,出力先を指定したtxtに変更(re-direct)するshellの機能

: cat hello_name.txt

で中身をcat(con-cat-inate)できる.

よく使うやつ復習

emacs

C-x,C-s 保存
C-x,C-c 終了
C-z 一時中断
fg 一度中断したprocessを再度起動させる
ps processの状況を確認

shell

mkdir ディレクトリ作成\
cd カレントディレクトリ変更
cat ファイルの内容を表示

参考


  • source ~/Desktop/grad_members_20f/members/mm-cell/post_org/c1_puts.org
13
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
13
0