Skip to content

Instantly share code, notes, and snippets.

View shinokada's full-sized avatar

Shinichi Okada shinokada

View GitHub Profile
a = [[1, 2, 'apple'], [2, 6, 'banana'], [3, 10, 'egg']]
for no, num, item in a
p "Shopping list #{no}: #{num} #{item}"
end
@data = [
["M" , 1000],
["CM" , 900],
["D" , 500],
["CD" , 400],
["C" , 100],
["XC" , 90],
["L" , 50],
["XL" , 40],
["X" , 10],
# strange splat
[*0..9] # [1,2,3,4,5,6,7,8,9]
# http://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/
# splat creates an array
first, *list = [1,2,3,4] # first= 1, list= [2,3,4]
*list, last = [1,2,3,4] # list= [1,2,3], last= 4
first, *center, last = [1,2,3,4] # first= 1, center= [2,3], last=4
a = *"Hello" #=> ["Hello"]
[1,2,3,4].inject(:+) # 10
[1,2,3,4].inject:+ # 10
#!/usr/bin/ruby
# http://zetcode.com/lang/rubytutorial/io/
$stdout = File.open "output.log", "a" # redirect a standard output to a log file.
puts "Ruby"
puts "Java"
$stdout.close
$stdout = STDOUT # Use predefined standard constant STDOUT to recreate the normal standard output
puts "Python"
# http://batsov.com/articles/2013/12/04/using-rubys-each-with-object/
nums = [1, 1, 2, 3, 3, 5]
nums.each_with_object(Hash.new(0)) { |e, a| a[e] += 1 }
# => {1=>2, 2=>1, 3=>2, 5=>1}
nums = [1, 1, 2, 3, 3, 5]
nums.reduce(Hash.new(0)) { |a, e| a[e] += 1; a }
# => {1=>2, 2=>1, 3=>2, 5=>1}
# http://blog.flatironschool.com/post/35154441787/rubys-each-with-object
hash = {}
['red', 'green', 'blue'].each do |color|
hash[color] = 'primary'
end
# Using inject, we don't have to initialize the hash ahead of time
['red', 'green', 'blue'].inject({}) do |hash, color|
# I struggled how to add input data to an array in a hash value and these art some
# ways to do. [See more examples](http://judge.u-aizu.ac.jp/onlinejudge/solution.jsp?pid=0105#6).
#Using an array hash[word] = [page.to_i]
# and using has_key?
hash = {}
while n = gets
word, page = n.split
hash.has_key?(word) ? hash[word] << page.to_i : hash[word] = [page.to_i]
end
r = 10..1
p (r.first).downto(r.last).to_a
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
p (1..10).reverse_each.to_a
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
@shinokada
shinokada / nested_object_namespacing_with_the_object_literal_pattern
Created January 7, 2013 03:17
nested object namespacing with the object literal pattern from Developing Backbone.js Applications p31.
var galleryApp = galleryApp || {};
// perform similar check for nested children
galleryApp.routers = galleryApp.routers || {};
galleryApp.model = galleryApp.model || {};
galleryApp.model.special = galleryApp.model.special || {};
// routers
galleryApp.routers.Workspace = Backbone.Router.extend({});
galleryApp.routers.PhotoSearch = Backbone.Router.extend({});
// models