ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

「RailsによるアジャイルWebアプリケーション開発」15章まで読了

Active Supportいろいろ。
以下のコードはRails外でも動きます。

require 'rubygems'
require 'active_support'

Rating = Struct.new(:name, :ratings)
rating = Rating.new("Rails", [10, 10, 9.5, 10])

puts rating.to_json
puts rating.to_yaml

hash = {1=>"abc", 2=>"cde"}
puts hash.to_xml

結果はこう。

>ruby test.rb
ruby test.rb
["Rails", [10, 10, 9.5, 10]]
--- !ruby/struct:Rating 
name: Rails
ratings: 
- 10
- 10
- 9.5
- 10
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <1>abc</1>
  <2>cde</2>
</hash>


リスト.group_by / index_byの例

require 'rubygems'
require 'active_support'
require 'pp'

Post = Struct.new(:author_id, :author)
p1 = Post.new(1, "Taka")
p2 = Post.new(2, "Taki")
p3 = Post.new(3, "Taku")
p4 = Post.new(1, "Taka")
p5 = Post.new(3, "Taku")

postList = [p1, p2, p3, p4, p5]
postHashByAuthorId = postList.group_by {|post| post.author_id}

pp postHashByAuthorId

puts "----------"

postHashByAuthorName = postList.group_by {|post| post.author}

pp postHashByAuthorName

puts "----------"

postHashIndexByAuthorId = postList.index_by {|post| post.author_id}

pp postHashIndexByAuthorId

結果はこう。

>ruby test2.rb
ruby test2.rb
{1=>
  [#<struct Post author_id=1, author="Taka">,
   #<struct Post author_id=1, author="Taka">],
 2=>[#<struct Post author_id=2, author="Taki">],
 3=>
  [#<struct Post author_id=3, author="Taku">,
   #<struct Post author_id=3, author="Taku">]}
----------
{"Taki"=>[#<struct Post author_id=2, author="Taki">],
 "Taku"=>
  [#<struct Post author_id=3, author="Taku">,
   #<struct Post author_id=3, author="Taku">],
 "Taka"=>
  [#<struct Post author_id=1, author="Taka">,
   #<struct Post author_id=1, author="Taka">]}
----------
{1=>#<struct Post author_id=1, author="Taka">,
 2=>#<struct Post author_id=2, author="Taki">,
 3=>#<struct Post author_id=3, author="Taku">}

group_byは、SQLのGROUP BYにも似たりですね。
index_byは、重複は削除されてしまうようです。


Rubyシンボルの拡張

postHashIndexByAuthorId = postList.index_by {|post| post.author_id}
は、
postHashIndexByAuthorId = postList.index_by(&:author_id)
とも書けますよ

というお話。


Procって、いわゆるlambdaってやつですかね?

class Symbol
  def to_proc
    Proc.new { |obj, *args| obj.send(self, *args) }
  end
end

なんとなく分かるような、分からないような。。


Rubyリファレンスマニュアルも読んだ。
http://www.ruby-lang.org/ja/man/html/Proc.html
なんとなく分かるような、分からないような。。