rubyで関数ポインタが使えるのか?

  • ruby 1.8.7
  • MacOS 10.8.2
#!/bin/env ruby

class Calcurator
	def initialize(a,b)
		@a=a
		@b=b
	end 
	def add 
		p @a+@b
	end 
	def subRet
		return @a-@b
	end 
	def addValue(c,d)
		p @a+@b+c+d
	end 
	def addValueRet(c)
		return @a+@b+c
	end 
	def addMethod(m)
		return @a+@b+method(m).call
		
	end 
end

class CalcTest
	def exec
		calc=Calcurator.new(2,1)
		calc.method(:add).call			 
		p calc.method(:subRet).call	
		calc.method(:addValue).call(3,4) 
		p calc.method(:addValueRet).call(4)	
		p calc.method(:addMethod).call(:subRet) 
	end 
end

if __FILE__ == $0 then
	CalcTest.new.exec
end

結果

3
1
10
7
4

ruby-mysqlで文字コード指定

rubyでMYSQLにつなぐ際にMySQL/Rubyを使っていたのですが、どうやら開発が止まってしまったらしくruby1.9には非対応とのこと

https://github.com/tmtm/ruby-mysql

こちらからruby-mysqlなるものをダウンロード。

ちなみにプロキシ越しのgemではうまくいきませんでした

# gem install ruby-mysql
WARNING:	Error fetching data: too many connection resets (http://rubygems.org/latest_specs.4.8.gz)
ERROR:	Could not find a valid gem 'ruby-mysql' (>= 0) in any repository
ERROR:	Possible alternatives: ruby-mysql

とりあえずインストール

# ruby setup.rb
  • 日本語

mysqlにはSjisでデータが入っており、クライアントがutf-8の場合には以下のように書く必要があります

#/bin/env ruby -w -Ku
# -*- coding=utf-8 -*-
client=Mysql.connect("localhost","root","pass","dbname")
client.charset="utf8"
res=client.query("select id,name from IdTable")
res.each{|r|
p r
}

memcachedで日本語キーを扱う

memcachedの代わりにkyoto tycoonを試してみようとしています。

kyoto tycoonはmemcachedと同じインターフェースで起動できるとのことで、当然memcachedライブラリが使えます

日本語のキーが使えるかどうか確認します

  • memcachedライブラリ
$ su
# export http_proxy=proxy:port
# gem install memcached
#!/bin/env ruby -Ku 
# -*- encoding:utf-8 -*-
require "rubygems"
require "memcached"
require "nkf"

cache=Memcached.new "localhost:11211"
cache.set("sony","6758",0)
puts cache.get("sony")
key="ソニー"
cache.set(key,"ソニー",0)
puts cache.get(key)
$ ruby mem.rb 
6758
/Library/Ruby/Gems/1.8/gems/memcached-1.5.0/lib/memcached/memcached.rb:630:in `reraise': Key {"ソニー"=>nil} (Memcached::ABadKeyWasProvidedOrCharactersOutOfRange)
	from /Library/Ruby/Gems/1.8/gems/memcached-1.5.0/lib/memcached/memcached.rb:608:in `check_return_code'
	from /Library/Ruby/Gems/1.8/gems/memcached-1.5.0/lib/memcached/memcached.rb:306:in `set'
	from mem.rb:11

なんかだめ。。

ちなみにperlだと

#!/usr/bin/perl

use strict;
use warnings;
use Cache::Memcached::Fast;

my $memd=Cache::Memcached::Fast->new({
		servers => [ { address => 'localhost:11211' }], 
}); 

# 値を追加 key => value
my $key='ソニーal';
$memd->set($key=> 'そにー2');

# 値を取得
my $id = $memd->get($key);
print "$id\n";
$ perl mem.pl
そにー2

rubyのライブラリが悪いようだ

ちなみにOSはMountain Lion