Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/a9c192b291345628134e to your computer and use it in GitHub Desktop.
Save shuhei/a9c192b291345628134e to your computer and use it in GitHub Desktop.
Hello, Ruby!

ターミナル入門

ディレクトリ構造

# ルートディレクトリ
/

# ホームディレクトリ
/Users/shuhei

ディレクトリの移動

# 今いるディレクトリ
pwd

# 今いるディレクトリのファイル一覧
ls

# 隠しファイルと詳細情報も一緒に
ls -al

# 容量を人間らしく表示
ls -alh

# 今いるディレクトリを hoge に移動
cd hoge

# ホームディレクトリに移動
cd ~
cd

# タブを押すと、ファイルパスを補完してくれる

# 今いるディレクトリの下の foo
ls ./foo

# 今いるディレクトリの上のディレクトリの下の foo
ls ../foo

ファイル・フォルダの作り方

# foo というディレクトリを作る
mkdir foo

# 入れ子状のディレクトリ構造を作る
mkdir -p foo/bar/baz
# foo というファイルを作る(ただし、空)
touch foo

# foo というファイルに Hello と書き込む。
echo 'Hello' > foo

# foo というファイルに Hello と追記。
echo 'Hello' >> foo
# foo.txt を bar.txt に改名
mv foo.txt bar.txt

# foo/foo.txt を bar ディレクトリの中に移動
mv foo/foo.txt bar/
# foo.txt を bar.txt という名前でコピー
cp foo.txt bar.txt

# foo ディレクトリを中身ごと bar という名前でコピー
cp -r foo bar
# foo.txt を削除
rm foo.txt

# foo ディレクトリを中身ごと削除(ゴミ箱にも入らず消滅するので注意!)
rm -r foo

# foo ディレクトリを中身ごと削除(確認なし)(要注意!)
rm -rf foo
# bar という名前の foo へのシンボリックリンクを作成
ln -s foo bar

コマンドの実行

コマンドはファイル。実行権限がついてるもの。 基本は、フルパスを指定。 ただし、環境変数 PATH に入っているディレクトリ下のコマンドは、名前だけで実行できる。

# PATH の中身を出力
echo $PATH

# PATH の追加
export PATH=~/bin:$PATH

# ls コマンドを実行
ls

# ls コマンドのありかを表示
which ls

# ls コマンドをフルパスで実行
/bin/ls

# ls コマンドのパーミッションを確認
ls -l /bin/ls

複数のコマンドをまとめて実行

echo "echo 'Let us ls'" >> hello.sh
echo "ls" >> hello.sh
echo "echo 'Done' >> hello.sh

bash hello.sh

便利なコマンド

# foo.txt の内容を出力
cat foo.txt

# foo.txt の中から hello を検索
grep hello foo.txt
# 今いるディレクトリを開く(Finder)
open .

# index.html を開く(ブラウザ)
open index.html
# 自分のマシンの IP アドレスを確認
ifconfig

# ネットワークの接続確認
ping google.com
# foo.txt の内容をクリップボードにコピー
cat foo.txt | pbcopy

# クリップボードの内容を bar.txt に書き込み
pbpaste > bar.txt
# Sublimet Text のコマンドを PATH に追加
echo 'export PATH="/Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin:$PATH"' >> ~/.bash_profile

# Sublime Text で今いるディレクトリを開く
subl .
# インストールが必要
brew install tree

# 今いるディレクトリ以下をツリー表示
tree
# インストールが必要
brew install sl

# ???
sl

Ruby 入門

何ができるか?

基本的に、コンピュータでできることはだいたい何でもできる(?)。得意なのは、テキスト処理やネットワーク関係、DSL(設定ファイルのようなプログラム)など。画像処理などもやればできる。

Input -> Output

以下、よくある使われ方。

  • Web アプリ - 有名な Ruby on Rails はこれを作るためのもの。HTTP リクエストを受けて、HTML などを返す。
  • Bot - 自動的に何かをする。Twitter に投稿するとか。Skype に返事をするとか。
  • 開発ツール - Compass など。ターミナルで動くコマンド。大体ファイルを変更したり、作ったり。(最近のフロントエンド開発ツールは JavaScript で書かれ Node.js で動作するものが多い。)
  • スクレイピング - Web サイトからコンテンツを取得、加工してファイルやデータベースなどに出力する。
  • API からデータ取得 - Mashup 的な。

他にも・・・

  • 画像処理
  • 機械学習
  • ゲーム
  • Mac のアプリを操る
  • Processing 的なやつ
  • ソケット通信でマイコンを操る

などなど、発想・組み合わせ次第でいろいろなことができる!

事例

Web アプリ・サービス

  • (かつての)Twitter - Ruby on Rails で作られていた。
  • Github - Ruby on Rails で作られている。
  • Basecamp - タスク共有システム。Ruby on Rails の開発元である 37 Singals のサービス。
  • 他にも Groupon, Square, Airbnb, Slideshare などなどの Web サービスは Ruby on Rails 製。

その他

  • 橋本商会 - Ruby を使ってデバイス制御など、いろいろ実験的なことをしている人のブログ。

自分の事例

インストール

Homebrew のインストール(管理者権限が必要)

まず AppStore から Xcode をインストール。そして、以下で Command Line Tools をインストール。

xcode-select --install

できたら、いよいよ Homebrew をインストールする。

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

rbenv, Ruby のインストール

brew install rbenv
brew install ruby-build
# インストール可能な Ruby のバージョンを確認
rbenv install -l

# 2.1.2 をインストール
rbenv install 2.1.2

# 2.1.2 を普段使う Ruby に指定
rbenv global 2.1.2

# Ruby のコマンドを更新
rbenv rehash
# よく使う bundle コマンドをインストールしておく
gem install bundler
rbenv rehash

使ってみる

初めての Ruby プログラム。書いたら ruby コマンドで実行する。

echo "puts 'hi form Ruby'" > hi.rb
ruby hi.rb

ちょこちょこ試す。Chrome などの Developer Console のようなもの。

irb

Web アプリを作ってみよう

# プロジェクト用のディレクトリを作成
mkdir hello_ruby
cd hello_ruby

# 超簡単に Web アプリが作れるライブラリをインストール
gem install sinatra
gem install haml

# hello.rb を書いてみよう
# 別のエディタでも、もちろん OK
subl hello.rb
# 書けたら、実行してみる
ruby hello.rb

# 別のターミナルで・・・(ブラウザで http://localhost:4567 を開く)
open http://localhost:4567/hello

ちゃんとした HTML, CSS, JS を使うには

Ruby のプログラムの中で HTML を作るのは大変。テンプレートを使う。テンプレートは views の中に置いておく。例では二種類を使用。

  • erb - 普通の HTML に値を埋め込む。
  • haml - HTML を簡単に書くための文法。慣れると速い。Rails などでよく使われる。

CSS, JS などのファイルは public というディレクトリに置いておくと、使えるようになる。

これらの例を手っ取り早く試すには、この Gist をレポジトリとして git clone してから setup.sh を実行する。

git clone this_gist_repo hello_ruby
cd hello_ruby
bash setup.sh

参考

require 'sinatra'
# Hello, World!
get '/hello' do
'Hello, World!'
end
# Introduce randomness!
get '/omikuji' do
fortunes = %w(大吉 中吉 吉 小吉 凶)
size = fortunes.size
index = rand(size)
fortune = fortunes[index]
"今日の運勢は#{fortune}です。"
end
# Make the box sing!
# Find a security hole!
get '/say' do
word = params[:word]
`say #{word}` if word
'<a href="/say?word=hello">hello</a><br><a href="/say?word=konnichiwa">konnichiwa</a>'
end
# Let's create a form!
comments = []
get '/bbs' do
comment_list = comments.join('<br>')
form = '<form method="POST" action="/bbs"><input type="text" name="comment"><input type="submit" value="comment"></form>'
comment_list + form
end
post '/bbs' do
comment = params[:comment]
comments << comment if comment
redirect to('/bbs')
end
# Template and static files.
get '/haml' do
@message = 'Hello, HAML!'
haml :hello
end
get '/erb' do
@message = 'Hello, ERB!'
erb :hello
end
# Index
get '/' do
@routes = %w(hello omikuji say bbs haml erb)
haml :index
end

スクレイピング入門

Web ページから情報を抽出すること。API など綺麗なデータが提供されていない場合に行う。

スクレイピングの課題

  • HTML の構造が変わると、それまで動いていたスクリプトが動かなくなる。
  • ログインしないと見られないサイト。
  • 頻繁にアクセスしすぎるとブロックされる可能性。また、サイトが落ちて訴訟になったりも・・・。
  • User Agent や Referrer を見て、ブラウザからの通常のアクセスかチェックされている場合もある。
  • 著作権の問題。

おすすめの方法

あたかも人がアクセスしているかのように、ある程度の間隔をおいて、リンクを辿りながらアクセスする。

Ruby なら Mechanize を使うと簡単。説明はこちら

gem install mechanize

試しに Google のトップページ上のリンクを取得してみる。

require 'mechanize'
require 'json'

agent = Mechanize.new
page = agent.get('http://google.com')

# Save as CSV
open('links.csv', 'w') do |f|
  page.links.each do |link|
    f.puts [link.text, link.href].join(', ')
  end
end

# Save as JSON
links = page.links.map do |link|
  { text: link.text, href: link.href }
end
json = JSON.generate(links)

open('links.json', 'w') do |f|
  f.puts json
end

https://github.com/shuhei/webland-scraper

  1. 国土交通省地価公示・都道府県地価調査から地価情報を収集。
  2. Bing Maps APIで各地点の住所を緯度経度に変換。
  3. JSON にして出力。
(function() {
var main = document.querySelector('.main-section');
var message = document.createElement('p');
message.className = 'message message-js';
message.innerText = 'Hello from JavaScript!';
main.appendChild(message);
})();
body {
font-family: sans-serif;
font-size: 16px;
padding: 0;
margin: 0;
}
.theme-blue {
background-color: #cff;
}
.theme-red {
background-color: #fcc;
}
.main-section {
width: 900px;
margin: 1em auto;
padding: 1em;
background-color: #fff;
}
.message {
border: 1px solid #ccc;
padding: 1em;
}
.message-js:before {
content: 'JavaScript says: ';
font-weight: bold;
}
.theme-blue .message-js:before {
color: #099;
}
.theme-red .message-js:before {
color: #c33;
}
#!/usr/bin/env bash
mv 03_hello.rb hello.rb
mkdir -p public views
mv public_app.js public/app.js
mv public_style.css public/style.css
mv views_index.haml views/index.haml
mv views_hello.erb views/hello.erb
mv views_hello.haml views/hello.haml
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><%= @message %></title>
<link rel="stylesheet" href="style.css">
</head>
<body class="theme-red">
<section class="main-section">
<h1 class="site-title">ERB Template</h1>
<p class="message"><%= @message %></p>
</section>
<script src="app.js"></script>
</body>
</html>
!!!
%html
%head
%meta(charset="UTF-8")
%title= @message
%link(rel="stylesheet" href="style.css")
%body.theme-blue
%section.main-section
%h1.site-title HAML Template
%p.message= @message
%script(src="app.js")
!!!
%html
%head
%title Hello, Ruby!
%link(rel="stylesheet" href="style.css")
:css
body {
font-size: 32px;
}
%body
%section.main-section
%h1 Hello, Ruby!
%ul
- @routes.each do |route|
%li
%a(href="/#{route}")= route
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment