Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

名古屋Ruby会議01 - Rubyでライフハッキング10連発♪

1,709 views

Published on

すみません10連発じゃなくて、Ruby 1.9 を使おうよ!って内容になってます。

Published in: Technology
  • Be the first to comment

  • Be the first to like this

名古屋Ruby会議01 - Rubyでライフハッキング10連発♪

  1. 1. require 'win32ole' app = WIN32OLE.new('Excel.Application') book = app.Workbooks.Open(app.GetOpenFilename) for row in book.ActiveSheet.UsedRange.Rows do for cell in row.Columns do p cell.Name p cell.Age end end book.close(false) app.quit via http://jp.rubyist.net/magazine/?0027-ExcellentRuby
  2. 2. require "yaml" people = [] for row in book.ActiveSheet.UsedRange.Rows do for cell in row.Columns do people << {:name => cell.Name, :age => cell.Age} end end File.open 'people.yml', 'w' do |file| YAML.dump(people, file) end
  3. 3. require 'yaml' people = YAML.load_file 'people.yml' people.each do |person| p = Person.new person p.save end import.rb ruby script/runner import.rb
  4. 4. u=' ' u.encoding # => #<Encoding:UTF-8> s = u.encode(‘Shift_JIS’) s.encoding # => #<Encoding:Shift_JIS>
  5. 5. # Ruby 1.9 " "[0..2] # => " " # Ruby 1.8 " "[0..2] # => "343201214"
  6. 6. $ cat hello.rb p" " $ ruby1.9 hello.rb hello.rb:1: invalid multibyte char (US-ASCII)
  7. 7. $ cat hello.rb # vim:fileencoding=utf-8 p" " $ ruby1.9 hello.rb " "
  8. 8. vim # vim:fileencoding=utf-8 emacs # -*- coding: utf-8 -*-
  9. 9. [1, 2, 3].combination(2).to_a # => [[1, 2], [1, 3], [2, 3]] [1, 2, 3].permutation(2).to_a # => [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
  10. 10. [1, 2].product([3, 4]) # => [[1, 3], [1, 4], [2, 3], [2, 4]] flatten [1, [2, [3]]].flatten(1) # => [1, 2, [3]] # Ruby 1.8 # => [1, 2, 3]
  11. 11. [0, 1, 2, 3].shuffle # => [1, 3, 0, 2] [0, 1, 2, 3].shuffle # => [2, 0, 3, 1] [0, 1, 2, 3].sample # => 2 [0, 1, 2, 3].sample(2) # => [3, 2]
  12. 12. [0, 1, 2, 3].take(2) # => [0, 1] [0, 1, 2, 3].drop(1) # => [1, 2, 3]
  13. 13. # Ruby 1.8 [1,2,3,4,5].inject(0) {|result, i| result + i} # => 15 # 1.9 [1,2,3,4,5].inject(:+) # => 15 # reduce alias [1,2,3,4,5].reduce(:+) # => 15
  14. 14. 2 w data = (1..100).map{rand(5)+1}.map{|id| {:id => id, :value => rand(10000)}} (1..5).map{|i| {:id => i, :sum => data.select{|h| h[:id] == i}.map{|h| h[:value]}.reduce(:+)}}

×