Skip to content

Instantly share code, notes, and snippets.

@igaiga
igaiga / sum_up.rb
Created May 24, 2012 13:56
ある配列が与えられたとき、3以下の要素がいくつあるか数えるコード
# -*- coding: utf-8 -*-
#ある配列が与えられたとき、Array [6,2,3] の中で3以下の数字の数を表示するコードを書いてください。
array = [6,2,3]
count = 0
array.each do |i|
count += 1 if i <= 3
end
p count
# 別解
@igaiga
igaiga / mod_hash.rb
Created May 24, 2012 13:57
Hashの特定条件下でvalueを変える
# -*- coding: utf-8 -*-
# Hash のキーの中に a という文字が含まれるときに、そのバリューを大文字に変換したHashを作るコードを書いてください。
# {:alice=>"year!", :bob=>"yo!", :linda => "wow!" }
# {:alice=>"YEAR!", :bob=>"yo!", :linda => "WOW!" }
h = {:alice=>"year!", :bob=>"yo!", :linda => "wow!" }
h.each do |key, value|
h[key] = value.upcase if key =~ /a/
end
p h
@igaiga
igaiga / hash_to_array.rb
Created May 24, 2012 13:57
[[:alice, "ALICE"], [:bob, "BOB"]] を {:alice => "ALICE, :bob => "BOB"} へ変換するコードを書いてください。
# -*- coding: utf-8 -*-
# [[:alice, "ALICE"], [:bob, "BOB"]] を
# {:alice => "ALICE, :bob => "BOB"} へ変換するコードを書いてください。
# この問題おそらく正答率低いはず。
array = [[:alice, "ALICE"], [:bob, "BOB"]]
h = {}
result = array.each do |i|
h[i[0]] = i[1]
end
# ファイル読み込み
included = [] # 出力用データを格納するArray
in_filename = 'in.txt'
File.open(in_filename, 'r:UTF-8') do |in_file|
while text = in_file.gets
included << text if text =~ /a/
end
end
# ファイルへ書き込み
# -*- coding: utf-8 -*-
# Excelファイルを読み書きするgem "spreadsheet" sample code
# gem install spreadsheet
require "spreadsheet"
# 新規作成
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet
sheet[0,0] = "testing..."
book.write("example.xls")
@igaiga
igaiga / twitter_search_api.rb
Last active October 6, 2015 08:58
twitter gem
# https://github.com/sferik/twitter
# $ gem install twitter
require 'twitter'
# set tokens
# https://dev.twitter.com/apps
Twitter.configure do |config|
config.consumer_key = YOUR_CONSUMER_KEY
config.consumer_secret = YOUR_CONSUMER_SECRET
@igaiga
igaiga / zip.rb
Created October 19, 2012 07:42
Array#zip
arr1 = ["1","2","3"]
arr2 = ["1x","2x","3x"]
text = "100"
arr1.zip(arr2) do |x|
text.gsub!(x[0], x[1])
end
p text #=> "1x00"
@igaiga
igaiga / standard_errors.rb
Created October 30, 2012 08:25
StandardErrorのサブクラス全表示
# thanks kwappa-san!
puts Object.constants.find_all { |c|
(cc = Object.const_get(c)) && # シンボルからクラス定数を取得
cc.respond_to?(:ancestors) && # ancestorsメソッドを持つ
cc.ancestors.include?(StandardError) # StandardErrorとそのサブクラス
}.sort
@igaiga
igaiga / gist:4065524
Created November 13, 2012 12:32
RubyConf2012レポート Xiki
Xiki: the Rubyfied Next-Generation Shell Console
公式サイト:http://xiki.org/
動画:http://www.confreaks.com/videos/1297-rubyconf2012-xiki-the-rubyfied-next-generation-shell-console
名前は"Xiki == executable wiki" でwikiになっていますが、
狙っているのは "Next-Generation Shell Console" なのだそうです。
エディタ上で動作して、Rubyのコード、shellコードが実行できたり、
wikiのように入れ子になったドキュメントを開いたり閉じたりして閲覧できます。
エディタ上でインタラクティブに動作するので、便利な使い道を考えるのが面白いと思いました。
@igaiga
igaiga / bingo.rb
Created November 18, 2012 04:24
bingo
(1..75).to_a.shuffle.each {|n| print n; STDIN.gets}