ラベル Ruby の投稿を表示しています。 すべての投稿を表示
ラベル Ruby の投稿を表示しています。 すべての投稿を表示

2016年9月24日土曜日

ファイルの中身を逆順にするRubyスクリプト

ぐぐってみたけど、しっくりくるものが見つからなかったので、載せておきます。
プログラミング授業の課題でありそうなので、参考にしてください。
#!/usr/local/bin/ruby
require 'fileutils'

orgFile = "original.txt"
newFile = "new.txt"

File.open(newFile, "w") do |new_f|
  File.open(orgFile) do |org_f|
    lines = org_f.readlines # ファイルの中身を一行ずつ読み込み、配列に格納する
    lines.reverse!          # 配列の中身の順序を入れ替える
    lines.each do |s|
      new_f.puts(s)         # 配列の中身を一行ずつファイルに書き込む
    end
  end
end

実行すると、こんな感じになります。
# cat original.txt
1, aaa
2, bbb
3, ccc
# ruby  reverse.rb
# cat new.txt
3, ccc
2, bbb
1, aaa

もちろん、色々なやり方があると思いますが、自分は上のやり方がわかりやすいと思いました。

2015年3月1日日曜日

cronでRubyから呼び出しているコマンドが実行できなくなった

cronに登録していたRubyスクリプトがうまく実行されなくなってことがあったので、メモ。

cronに登録したコマンドの実行に失敗した場合、実行ユーザー宛にメールが届く。
(定義ファイル自身に誤りがあれば、/var/log/cronに書かれる。)

メールの内容を見ると、以下のようになっていた。(一部省略)
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
X-Cron-Env: <USER=root>

/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:60: command not found: pcsensor -c
'pcsensor'というコマンドをRubyから実行しているが、これが見つからないよう。
直接、Rubyスクリプトを実行したときには問題なく実行できるのに。。

PATHが/usr/bin, /bin しかないので、それ以外のパスに格納されたコマンドが実行されないと推測。
Rubyスクリプトの呼び出し方法を以下のように修正。

# result =  `pcsensor -c`
result =  `/usr/local/bin/pcsensor -c`

この後は問題なく上記スクリプトが正しく動作し、cronのエラーも表示されなくなった。

しかし、なぜ急に実行されなくなったか不明。なにかいじったかな。。

2015年2月9日月曜日

Macでrbenvを使ってRubyをインストールしてみる

rvmがなぜか消えてたので、rbenvを入れてみる。
(seppukuした形跡があった。。)

MacなんでHomebrewでインストールしちゃる。


$ brew install rbenv                                 [~]
==> Downloading https://github.com/sstephenson/rbenv/archive/v0.4.0.tar.gz
######################################################################## 100.0%
==> Caveats
To use Homebrew's directories rather than ~/.rbenv add to your profile:
export RBENV_ROOT=/usr/local/var/rbenv

To enable shims and autocompletion add to your profile:
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi
==> Summary
🍺  /usr/local/Cellar/rbenv/0.4.0: 31 files, 152K, built in 3 seconds

$ brew install ruby-build                            [~]
==> Installing dependencies for ruby-build: autoconf, pkg-config, openssl
==> Installing ruby-build dependency: autoconf
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/autoconf-2.
######################################################################## 100.0%
==> Pouring autoconf-2.69.mavericks.bottle.1.tar.gz
🍺  /usr/local/Cellar/autoconf/2.69: 69 files, 2.0M
==> Installing ruby-build dependency: pkg-config
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/pkg-config-
######################################################################## 100.0%
==> Pouring pkg-config-0.28.mavericks.bottle.2.tar.gz
🍺  /usr/local/Cellar/pkg-config/0.28: 10 files, 604K
==> Installing ruby-build dependency: openssl
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/openssl-1.0
######################################################################## 100.0%
==> Pouring openssl-1.0.1i.mavericks.bottle.3.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
/usr/local/etc/openssl/certs

and run
/usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

The OpenSSL provided by OS X is too old for some software.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS:  -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.1i: 430 files, 15M
==> Installing ruby-build
==> Downloading https://github.com/sstephenson/ruby-build/archive/v20140919.tar.
######################################################################## 100.0%
==> ./install.sh
🍺  /usr/local/Cellar/ruby-build/20140919: 128 files, 548K, built in 3 seconds
$ brew install rbenv-gemset                          [~]
==> Downloading https://github.com/jf/rbenv-gemset/archive/v0.5.8.tar.gz
######################################################################## 100.0%
🍺  /usr/local/Cellar/rbenv-gemset/0.5.8: 12 files, 56K, built in 2 seconds
$ brew install rbenv-gem-rehash                      [~]
==> Downloading https://github.com/sstephenson/rbenv-gem-rehash/archive/v1.0.0.t
######################################################################## 100.0%
==> Downloading https://github.com/sstephenson/rbenv-gem-rehash/commit/0756890cf
######################################################################## 100.0%
==> Patching
patching file README.md
Hunk #1 succeeded at 23 (offset -2 lines).
patching file etc/rbenv.d/exec/~gem-rehash.bash
patching file gems/rbenv-gem-rehash-1.0.0/lib/rubygems_plugin.rb
patching file rubygems_plugin.rb
patching file specifications/rbenv-gem-rehash-1.0.0.gemspec
==> Caveats
If the GEM_PATH environment variable is undefined, rbenv-gem-rehash must
first execute the gem env gempath command to retrieve RubyGems' default path
so that it can can append to the path rather than override it. This can take
a while--from a few hundred milliseconds on MRI to several seconds on
JRuby--so the default path for the current Ruby version is cached to the
filesystem the first time it is retrieved.
==> Summary
🍺  /usr/local/Cellar/rbenv-gem-rehash/1.0.0: 7 files, 24K, built in 3 seconds
$ 


楽ちんでした。
あとは「rbenv install 2.0.0」とかでインストールできちゃう。
楽ちん。

2014年9月22日月曜日

Ruby関連(gemとかrailsとか)のメッセージの対処

gemとかRailsとか実行しようとすると、以下の警告メッセージが必ず表示されてた。

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/universal-darwin13/rbconfig.rb:212: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

「PATHの/usr/local/binが、mode040777になってて、書き込めて危ないよ。」ってことなので、/usr/local/binディレクトリを見ると、確かに権限が777になってた。

$ sudo chmod 744 /usr/local/bin

変更したあと、もう一度確認すると、今度は以下のメッセージが。

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/universal-darwin13/rbconfig.rb:212: warning: Insecure world writable dir /usr/local in PATH, mode 040777

/usr/localもかよ!ってことで、また権限変更。

$ sudo chmod 744 /usr/local

今度はメッセージが出なくなった。めでたしめでたし。

2014年4月30日水曜日

MacでRVMを使ったRuby環境の構築

環境は、MacBook ProのMavericks(10.9.2)です。
昔、Railsの記事を書いていた時があるし、RubyとかRails入ってたよなーとか思いながらチェックしたけど、Railsなんてインストールされてなかった。
よくよく考えてみたら、OSをクリーンインストールとかしてたから、消えちゃったのかも。。
と思って、あらためてRuby環境から作り直す。

まずはRVMのインストール。
本家サイトに書いてある方法に従う。
$ curl -L get.rvm.io | bash -s stable
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100   184  100   184    0     0    270      0 --:--:-- --:--:-- --:--:--   270
100 20511  100 20511    0     0  16292      0  0:00:01  0:00:01 --:--:--  241k
Downloading https://github.com/wayneeseguin/rvm/archive/stable.tar.gz

Installing RVM to /Users/***/.rvm/
Adding rvm PATH line to /Users/***/.profile /Users/***/.bashrc /Users/***/.zshrc.
RVM sourcing line found in /Users/***/.zshrc.
RVM sourcing line not found for Bash, rerun this command with '--auto-dotfiles' flag to fix it.
Installation of RVM in /Users/***/.rvm/ is almost complete:

* To start using RVM you need to run `source /Users/***/.rvm/scripts/rvm`
in all your open shell windows, in rare cases you need to reopen all shell windows.

# ***,
#
#   Thank you for using RVM!
#   We sincerely hope that RVM helps to make your life easier and more enjoyable!!!
#
# ~Wayne, Michal & team.

In case of problems: http://rvm.io/help and https://twitter.com/rvm_io

ここまではいいんだけど、次の手順で、以下を.bashrcに設定しろって言われてる。
[ -s ${HOME}/.rvm/scripts/rvm ] && source ${HOME}/.rvm/scripts/rvm

そもそもzsh使っているのに。。
と思ってぐぐったら、zshrcにも設定できた。
$ source ~/.rvm/scripts/rvm

これで、zshrcを再読み込みして、起動
$ source ~/.zshrc

いよいよRubyのインストール。
$ rvm install 1.9.2
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.9/x86_64/ruby-1.9.2-p320.
It is not possible to build movable binaries for rubies 1.8-1.9.2, but you can do it for your system only.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Installing requirements for osx.
Updating system - please wait
Error running 'requirements_osx_port_update_system ruby-1.9.2-p320',
showing last 15 lines of /Users/***/.rvm/log/1398601968_ruby-1.9.2-p320/update_system.log
checking whether rl_username_completion_function is declared... no
checking whether rl_filename_completion_function is declared... yes
checking whether rl_completion_matches is declared... yes
checking whether username_completion_function is declared... yes
checking whether filename_completion_function is declared... yes
checking whether completion_matches is declared... yes
checking for Tcl configuration... configure: error: Can't find Tcl configuration definitions
Command failed: cd /opt/local/var/macports/sources/rsync.macports.org/release/tarballs/base && CC=/usr/bin/cc ./configure --prefix=/opt/local --with-tclpackage=/Library/Tcl --with-install-user=root --with-install-group=admin --with-directory-mode=0755 --enable-readline && make && make install SELFUPDATING=1
Exit code: 1
DEBUG: Error installing new MacPorts base: command execution failed
while executing
"macports::selfupdate [array get global_options] base_updated"
Error: /opt/local/bin/port: port selfupdate failed: Error installing new MacPorts base: command execution failed
+__rvm_try_sudo:48> return 1
+requirements_osx_port_update_system:2> return 1
Requirements installation failed with status: 1.

エラーしました。何のエラーだろ?MacPortsとか出てるし…
ぐぐったら、MacPortsのアップデートに失敗したときに表示されるメッセージらしく、コマンドラインツールのインストールが必要らしい。
以下コマンドを実行し、ダイアログで「インストール」を選択する。
$ sudo xcode-select --install
xcode-select: note: install requested for command line developer tools

もう一回実行したら、成功した!
$ rvm install 1.9.2
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.9/x86_64/ruby-1.9.2-p320.
It is not possible to build movable binaries for rubies 1.8-1.9.2, but you can do it for your system only.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Installing requirements for osx.
Updating system - please wait
Installing required packages: curl-ca-bundle, autoconf, automake, libtool, pkgconfig, apple-gcc42, libiconv, libyaml, libffi, readline, libksba, openssl, sqlite3, zlib, gdbm, ncurses - please wait
Updating certificates in '/opt/local/etc/openssl/cert.pem'.
*** password required for 'mv -f /var/folders/5j/g68tsznn7wxgzrr008w1dc3h0000gp/T//tmp.3DZfmE03Q2GoC9I02F /opt/local/etc/openssl/cert.pem': 
Requirements installation successful.
Installing Ruby from source to: /Users/***/.rvm/rubies/ruby-1.9.2-p320, this may take a while depending on your cpu(s)...
ruby-1.9.2-p320 - #downloading ruby-1.9.2-p320, this may take a while depending on your connection...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100 8770k  100 8770k    0     0   258k      0  0:00:33  0:00:33 --:--:--  362k
ruby-1.9.2-p320 - #extracting ruby-1.9.2-p320 to /Users/***/.rvm/src/ruby-1.9.2-p320 - please wait
ruby-1.9.2-p320 - #applying patch /Users/***/.rvm/patches/ruby/GH-488.patch - please wait
ruby-1.9.2-p320 - #configuring - please wait
ruby-1.9.2-p320 - #post-configuration - please wait
ruby-1.9.2-p320 - #compiling - please wait
ruby-1.9.2-p320 - #installing - please wait
ruby-1.9.2-p320 - #making binaries executable - please wait
ruby-1.9.2-p320 - #downloading rubygems-2.2.2
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100  404k  100  404k    0     0   181k      0  0:00:02  0:00:02 --:--:--  181k
No checksum for downloaded archive, recording checksum in user configuration.
ruby-1.9.2-p320 - #extracting rubygems-2.2.2 - please wait
ruby-1.9.2-p320 - #removing old rubygems - please wait
ruby-1.9.2-p320 - #installing rubygems-2.2.2 - please wait
ruby-1.9.2-p320 - #gemset created /Users/***/.rvm/gems/ruby-1.9.2-p320@global
(eval):1: bad pattern: #*[[:space:]]+([[:space:]])
(eval):1: bad pattern: #*[[:space:]]+([[:space:]])
(eval):1: bad pattern: #*[[:space:]]+([[:space:]])
(eval):1: bad pattern: #*[[:space:]]+([[:space:]])
(eval):1: bad pattern: #*[[:space:]]+([[:space:]])
ruby-1.9.2-p320 - #importing gemset /Users/***/.rvm/gemsets/global.gems - please wait
ruby-1.9.2-p320 - #generating global wrappers - please wait
ruby-1.9.2-p320 - #gemset created /Users/***/.rvm/gems/ruby-1.9.2-p320
ruby-1.9.2-p320 - #importing gemsetfile /Users/***/.rvm/gemsets/default.gems evaluated to empty gem list
ruby-1.9.2-p320 - #generating default wrappers - please wait
ruby-1.9.2-p320 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
Install of ruby-1.9.2-p320 - #complete 
WARNING: Please be aware that you just installed a ruby that is no longer maintained (2014-02-23), for a list of maintained rubies visit:

http://bugs.ruby-lang.org/projects/ruby/wiki/ReleaseEngineering

Please consider upgrading to ruby-2.1.1 which will have all of the latest security patches.
Ruby was built without documentation, to build it run: rvm docs generate-ri

2014年3月1日土曜日

Linux環境で室温を定期的にツイートする

以前、USB温度計を使ってMRTGに表示する設定をしました。
MRTGの画面を見れば、家の外にいても室内の気温が見れるけど…ずっとHTTPのポート開放しておくのもメンドクサイし…

せっかくなので気温を定期的にtweetしてみる。
つぶやくためのTwitter側の設定と、つぶやく用の環境の設定がそれぞれ必要。

twitterのアカウントの準備

当たり前ですがtwitterのアカウントを準備する。

そして、外部APIからつぶやけるように、アカウントの設定を行う。
1. Twitter Appsにアクセスして、Twitterのアカウントでログイン。
2. 『Create an application』画面で各項目を入力し、アプリケーションを作成する。

アプリケーション名: 任意の名称
アプリケーションの説明: 説明を10文字以上
アプリケーションのウェブサイトURL: 自分のTwitterのURLなど
アプリケーションの種類: クライアントアプリケーションを選択
標準のアクセスタイプ: Read & Writeを選択
Twitterでログインする: チェックをつける

3. 表示される「Consumer key」と「Consumer secret」をメモする。

tweetできる環境を構築

rubyでつぶやきます。
この辺を参考にしました。↓
http://ramtiga.hatenablog.jp/entry/20110409/p1

TwitterのOAuth登録として、以下を実行する。
このとき、表示されるOAuthの「token」と「token_secret」をメモする。

# gem install oauth get-twitter-oauth-token
# get-twitter-oauth-token
Consumer Key: *****
Consumer Secret: *****
...
...
...
Token: *****    # ←tokenとしてメモ
Secret: *****   # ←token_secretとしてメモ

これで環境でつぶやけるようになった。
あとはRubyでつぶやくようのソースコードを準備する。
それほど難しくないけど。
#!/usr/local/bin/ruby
require 'rubygems'
require 'twitter'

CONSUMER_KEY       = "*****"  # Twitter Appsでメモした「Consumer key」の値
CONSUMER_SECRET    = "*****"  # Twitter Appsでメモした「Consumer secret」の値
ACCESS_TOKEN        = "*****" # OAuth登録でメモした「token」の値
ACCESS_TOKEN_SECRET = "*****" # OAuth登録でメモした「token_secret」の値

Twitter.configure do |config|
  config.consumer_key       = CONSUMER_KEY
  config.consumer_secret    = CONSUMER_SECRET
  config.oauth_token        = ACCESS_TOKEN
  config.oauth_token_secret = ACCESS_TOKEN_SECRET
end

# temperコマンド実行
result = `temper`
temp = result.split(",")[1]

# 日時取得
time = Time.now.strftime("%Y-%m-%d %H:%M:%S")

MSG1 = "["
MSG2 = "] の気温 : "

MSG = MSG1 + time + MSG2 + temp

Twitter.update(MSG)

これでつぶやけるようになりました。

cronに登録

あとはこのスクリプトを定期的に実行されるように設定する。
Linux環境なのでcronに登録しました。

# cat /etc/cron.d/tweetTemper
1,21,41 * * * * root /usr/local/bin/tweetTemper.rb

毎時1,21,41分につぶやくように設定。(0,20,40にすると、MRTGのupdateと重複してしまうため、わざと)

2011年3月30日水曜日

hotcocoaでGUIアプリ



Hotcocoaというフレームワーク(ライブラリ?)を見つける。
Rubyではなく、MacRubyに包括されているらしいです。
参考:http://www.textdrop.net/soft/macruby-03/

Cocoaプログラミングをやってくれるものらしく、簡単にGUIアプリが書けるらしい。
ということで、さっそく動かしてみようとするが、MacRubyが入っていない…。

手でインストールするんだけど、ソースコードしかない情報がたくさんあったけど、普通に公式サイトからzipをダウンロードして、パッケージからインストールしました。
参考:http://www.macruby.org/downloads.html

んでもって、macgemというgemではないモノがインストールされたので、これを利用してhotcocoaをインストール。 

$ sudo macgem install hotcocoa

ようやく実行出来る!って思って、以下のソースをコンパイル+実行してみる。

ソースコード:

$ cat hotcocoa_test.rb
require 'hotcocoa'
include HotCocoa

application do |app|

window :size => [100, 50] do |win|
b = button :title => 'Hello'
b.on_action { puts 'World!' }
win << b
end
end
コンパイル:
$ hotcocoa hotcocoa_test.rb
$ cd hotcocoa_test
$ ls
Rakefile config lib resources
$ macrake
(in /Users/***/Documents/prog/rb/hotcocoa_test)
ld: warning: in /Library/Frameworks//MacRuby.framework/MacRuby, file was built for unsupported file format which is not the architecture being linked (i386)
Undefined symbols for architecture i386:
"_macruby_main", referenced from:
_main in ccE6DYYW.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/93/93tYOnyhHwuzyA++XUKg5++++TI/-Tmp-//ccUq5GxN.out (No such file or directory)
/bin/sh: ./Hotcocoa Test.app/Contents/MacOS/HotcocoaTest: No such file or directory

あー、また何かエラー出てるよw
"i386"のメッセージ的に、x64環境だと何か設定が必要なのかも…。