blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
137
path
stringlengths
2
355
src_encoding
stringclasses
31 values
length_bytes
int64
11
3.9M
score
float64
2.52
5.47
int_score
int64
3
5
detected_licenses
listlengths
0
49
license_type
stringclasses
2 values
text
stringlengths
11
3.93M
download_success
bool
1 class
3b6f7c57238982a45fed3a5f997e36e0d63d7ef3
Ruby
mmrobins/project-euler-solutions
/049_prime_permutations.rb
UTF-8
918
2.953125
3
[]
no_license
require 'pp' require 'primality_testing' require 'set' class Array def to_i self.join.to_i end end module Enumerable def dups inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys end end permuted_primes_with_at_least_three_prime_permutations = [] 9999.primes_less_than.select {|n| n > 999}.each do |n| permuted_primes = n.to_list.permutation(4).map(&:to_i).select {|n| n.prime? && n > 999}.uniq permuted_primes_with_at_least_three_prime_permutations << permuted_primes if permuted_primes.size >= 3 end differences = [] permuted_primes_with_at_least_three_prime_permutations.map(&:to_set).uniq.each do |p_set| p_set.each do |p| p_set_copy = p_set.dup.delete(p).to_a #pp p_set_copy diffs = p_set_copy.map {|n| n - p} #pp "p #{p} p_set_copy #{p_set_copy.to_a} diffs #{diffs}" differences << p_set unless diffs.dups.empty? end end pp 'differences' pp differences
true
a2583e179c3a1a5aaef08c79445f499915b87c07
Ruby
ginnyfahs/whiteboarding-practice
/ruby/strings/substring_checker.rb
UTF-8
433
3.515625
4
[]
no_license
def substring_checker(a1, a2) substrings = [] i = 0 while i < a2.length j = 0 while j < a1.length if a2[i].include? a1[j] if !substrings.include? a1[j] substrings << a1[j] end end j +=1 end i +=1 end return substrings end a1 = ["arp", "live", "strong", "hello"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] p substring_checker(a1, a2)
true
14a389e44118ba8b09747cb7b063818d1dd8b158
Ruby
wjdix/resque-pool
/lib/resque/pool/logging.rb
UTF-8
377
2.6875
3
[ "MIT" ]
permissive
module Resque class Pool module Logging # Given a string, sets the procline ($0) # Procline is always in the format of: # resque-pool-master: STRING def procline(string) $0 = "resque-pool-master: #{string}" end # TODO: make this use an actual logger def log(message) puts message end end end end
true
4baf3ed9505bd6e3cdda9d4b991e8a3a51dcd2f3
Ruby
venelrene/Codewars
/tdd_kata/spec/string_calculator_spec.rb
UTF-8
1,680
3.890625
4
[]
no_license
require "string_calculator" describe StringCalculator do #We are using another describe block to describe the add class method. By convention, class methods are prefixed with a dot (".add"), and instance methods with a dash ("#add"). describe ".add" do #We are using a context block to describe the context under which the add method is expected to return zero. context is technically the same as describe, but is used in different places, to aid reading of the code. context "given '4'" do #We are using an it block to describe a specific example, which is RSpec's way to say "test case". Generally, every example should be descriptive, and together with the context should form an understandable sentence. This one reads as "add class method: given an empty string, it returns zero". it "return '4'" do #expect(...).to and the negative variant expect(...).not_to are used to define expected outcomes. The Ruby expression they are given (in our case, StringCalculator.add("")) is combined with a matcher to fully define an expectation on a piece of code. The matcher we are using here is eql, a basic equality matcher. expect(StringCalculator.add("4")).to eql(4) end end context "given '10'" do it "return '10'" do expect(StringCalculator.add("10")).to eql(10) end end context "two numbers" do context "given '2,4'" do it "return '6'" do expect(StringCalculator.add('2,4')).to eql(6) end end context "given '17, 100'" do it "return '117'" do expect(StringCalculator.add("17,100")).to eql(117) end end end end end
true
c1690eacdf853033ea02ce2a499caf5e41bde60b
Ruby
coffeencoke/fun
/lib/problems/ccipher.rb
UTF-8
469
3.34375
3
[ "MIT" ]
permissive
module CCipher def self.decode(message, shifts) message.each_char.with_index do |char, index| original_index = char.ord-alphabet_offset unshifted_index = original_index-1 - shifts new_index = unshifted_index % alphabet.size message[index] = alphabet[new_index] end message end def self.alphabet @alphabet ||= (1..26).map{|a| (a+alphabet_offset).chr } end def self.alphabet_offset @offset ||= "A".ord-1 end end
true
216d02a9e85e5c0cece72eeedd67a6ba3ad9c859
Ruby
mikemorton72/practice_ruby
/prework/song.rb
UTF-8
1,339
3.5625
4
[]
no_license
class Song def initialize(title, artist, lyrics) @song_title = title @song_artist = artist @song_lyrics = lyrics end def title=(str) @song_title = str end def artist=(str) @song_artist = str end def lyrics=(str) @song_lyrics = str end def title return @song_title end def artist return @song_artist end def lyrics return @song_lyrics end def info return "Artist: #{artist}\nTitle: #{title}\nLyrics: #{lyrics}" end end class Product def initialize(name,description,price) @name, @description, @price = name, description, price end def name @name end def description @description end def price @price end def name=(text) @name = text end def description=(text) @description = text end def price=(number) @price = number end def tax price*0.09 end def total price + tax end end newsong = Song.new("Friday", "Rebecca Black", "Gotta get down on Friday") puts newsong.info product = Product.new("Printer", "It prints pages!", 94) p product p product.name product.name = "Awesome Printer" p product.name p product.tax p product.total
true
737914e01aa65f50d2c1d1aafe53162599c1cc11
Ruby
Yoomee/ym-core
/lib/ym_core/model/date_accessor.rb
UTF-8
928
2.5625
3
[ "MIT" ]
permissive
module YmCore::Model::DateAccessor def self.included(base) base.extend(ClassMethods) end module ClassMethods def date_accessors(*args) options = args.extract_options! format = options[:format] || "%d/%m/%Y" args.each do |date_attr| self.validates("#{date_attr}_s", :date => true) define_method "#{date_attr}_s" do instance_variable_get("@#{date_attr}_s") || send(date_attr).try(:strftime, format) || '' end define_method "#{date_attr}_s=" do |value| if value.blank? write_attribute(date_attr, nil) else begin write_attribute(date_attr,Date.strptime(value, format)) rescue ArgumentError end instance_variable_set("@#{date_attr}_s",value) end end end end alias_method :date_accessor, :date_accessors end end
true
a8a4e16c41cbaf9991b12b8bad5b1b55aec94c82
Ruby
pbalzac/adventofcode-2020
/20/20.rb
UTF-8
4,170
3.125
3
[]
no_license
def rotate(grid) (grid.length - 1..0).step(-1).map { |i| grid.map { |row| row[i] }.join } end def flip(grid) grid.map { |row| row.reverse } end def match(side, g1, g2) if side == :bottom return g1[-1] == g2[0] else return g1.map { |row| row[-1] } == g2.map { |row| row[0] } end end def match_line(tiles, l1, l2) (0...l1.length).all? { |n| match(:bottom, tiles[l1[n][0]][l1[n][1]], tiles[l2[n][0]][l2[n][1]]) } end def get_line_tiles(l) l.map { |t| t[0] } end def printg(g) g.each { |row| puts row } puts end $dragon_coords = [ [18, 0], [0, 1], [5, 1], [6, 1], [11, 1], [12, 1], [17, 1], [18, 1], [19, 1], [1, 2], [4, 2], [7, 2], [10, 2], [13, 2], [16, 2] ] $dragon_w = 20 $dragon_h = 3 def find_dragons(image) here_be_dragons = Array.new (0..image.length - $dragon_h).each { |y| (0..image[0].length - $dragon_w).each { |x| if $dragon_coords.all? { |cx, cy| image[cy + y][cx + x] == '#' } here_be_dragons << [x, y] end } } here_be_dragons end def replace_dragons(image, dragons) dragons.each { |x, y| $dragon_coords.each { |dx, dy| image[y + dy][x + dx] = 'O' } } end def turbulence(image) image.map{ |l| l.count('#') }.reduce(:+) end def all(grid) all = Array.new all << grid all << rotate(grid) all << rotate(rotate(grid)) all << rotate(rotate(rotate(grid))) all += all.map { |g| flip(g) } all end def run(f) tiles = Hash.new { |h, k| h[k] = Array.new } current_tile = 0 File.read(f).lines(chomp: true).each { |line| case line when /Tile (\d+):/ current_tile = $1.to_i tiles[current_tile] = [] else tiles[current_tile] << line if !line.length.zero? end } tiles.keys.each { |key| tiles[key] = all(tiles[key]) } width = Integer.sqrt tiles.length pairs = [] tiles.each { |n, grids| remaining = tiles.keys - [n] grids.each.with_index { |grid, i| remaining.each { |r| tiles[r].each.with_index { |nx, j| if match(:right, grid, nx) pairs << [[n, i], [r, j]] end } } } } lines = pairs.dup ll = 2 while ll <= width - 2 next_lines = [] lines.each { |line| line_tiles = line.map { |t| t[0] } valid_next_pairs = pairs.filter{ |pair| (line_tiles & [ pair[0][0], pair[1][0] ]).empty? && match(:right, tiles[line[-1][0]][line[-1][1]], tiles[pair[0][0]][pair[0][1]]) } valid_next_pairs.each { |p| next_lines << line + p } } lines = next_lines ll += 2 end # handle odd width case line_pairs = [] lines.each { |line| line_tiles = get_line_tiles(line) valid_next_lines = lines.filter { |l| (line_tiles & get_line_tiles(l)).empty? && match_line(tiles, line, l) } valid_next_lines.each { |l| line_pairs << [ line, l ] } } line_groups = line_pairs.dup ll = 2 while ll <= width - 2 next_line_groups = [] line_groups.each { |lg| lg_tiles = lg.map { |l| get_line_tiles(l) }.flatten valid_next_lps = line_pairs.filter{ |lp| (lg_tiles & (get_line_tiles(lp[0]) + get_line_tiles(lp[1]))).empty? && match_line(tiles, lg[-1], lp[0]) } valid_next_lps.each { |lp| next_line_groups << lg + lp } } line_groups = next_line_groups ll += 2 end z = line_groups.map { |lg| [ lg[0][0][0], lg[0][-1][0], lg[-1][0][0], lg[-1][-1][0] ] } four_corners = z.map { |zz| zz.reduce(:*) }.uniq image = Array.new tile_size = tiles.values[0][0][0].length line_groups[0].each { |lg| (1...tile_size - 1).each { |i| image << lg.reduce('') { |a, t| a + tiles[t[0]][t[1]][i][1..-2] } } } rotations = all(image) final_image = nil dragons = nil rotations.each { |r| dragons = find_dragons(r) final_image = r break if !dragons.empty? } replace_dragons(final_image, dragons) printg(final_image) [ four_corners[0], turbulence(final_image) ] end
true
24935a535b6744bbe2ca7b5dc929b5b0277dab7e
Ruby
skilldrick/consideredharmful
/app/models/harmful.rb
UTF-8
1,030
2.890625
3
[]
no_license
require 'open-uri' require 'json' class Harmful attr_accessor :title, :title_no_formatting, :url def self.load_json key = "ABQIAAAAWLOrTtZZMVqckifzzqf5ExTJ4z6FYubmaJQBWq" key << "BMMbq6Cm7PQhTpBR48VC90aX3PtU5LEktkiQhpnw" rsz = 8 start = 0 search_method = 'blogs' search_method = 'web' q = "'considered%20harmful'" url = "http://ajax.googleapis.com/ajax/services/search/" url << search_method url << "?v=1.0&q=#{q}&rsz=#{rsz}&start=#{start}" ret = {} open(url) do |f| text = f.read ret = JSON.parse(text) end ret end def self.all harmfuls = [] json = load_json json['responseData']['results'].each do |result| harmful = Harmful.new harmful.title = result['title'] harmful.title_no_formatting = result['titleNoFormatting'] harmful.url = result['url'] harmfuls << harmful end harmfuls.map! do |harmful| bolds = harmful.title.scan(/<b>[^<\/b]*<\/b>/) if bolds.length > 0 harmful.title << bolds.length.to_s end harmful end harmfuls end end
true
b0503dc654c0bbddd62311a317f33fc9cb303960
Ruby
ericschoettle/ruby-week2-day2
/ruby_week2_day2/tamagotchi/spec/tamagotchi_spec.rb
UTF-8
3,022
3.03125
3
[]
no_license
require('rspec') require('Tamagotchi') describe(Tamagotchi) do before() do Tamagotchi.clear() end describe("#initialize") do it("sets the name and life levels of a new Tamagotchi") do my_pet = Tamagotchi.new("lil dragon") expect(my_pet.name()).to(eq("lil dragon")) expect(my_pet.food_level()).to(eq(10)) expect(my_pet.rest_level()).to(eq(10)) expect(my_pet.play_level()).to(eq(10)) end end describe("#is_alive") do it("is alive if the food level is above 0") do my_pet = Tamagotchi.new("lil dragon") expect(my_pet.is_alive?()).to(eq(true)) end it("is dead if the food level is 0") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_food_level(0) expect(my_pet.is_alive?()).to(eq(false)) end it("is dead if the play level is 0") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_play_level(0) expect(my_pet.is_alive?()).to(eq(false)) end it("is dead if the rest level is 0") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_rest_level(0) expect(my_pet.is_alive?()).to(eq(false)) end end describe("#set_food_level") do it("changes the food level") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_food_level(3) expect(my_pet.food_level()).to(eq(3)) end end describe("#set_rest_level") do it("changes the rest level") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_rest_level(3) expect(my_pet.rest_level()).to(eq(3)) end end describe("#set_play_level") do it("changes the play level") do my_pet = Tamagotchi.new("lil dragon") my_pet.set_play_level(3) expect(my_pet.play_level()).to(eq(3)) end end describe("#time_passes") do it("decreases the amount of food the Tamagotchi has left") do my_pet = Tamagotchi.new("lil dragon") my_pet.time_passes(1) #decide what trigger you will use to make time pass expect(my_pet.food_level()).to(eq(9)) end it("decreases the amount of rest the Tamagotchi has left by 0.5") do my_pet = Tamagotchi.new("lil dragon") my_pet.time_passes(1) #decide what trigger you will use to make time pass expect(my_pet.rest_level()).to(eq(9.5)) end it("decreases the amount of play the Tamagotchi has left by 1") do my_pet = Tamagotchi.new("lil dragon") my_pet.time_passes(1) #decide what trigger you will use to make time pass expect(my_pet.play_level()).to(eq(9)) end end describe(".find") do it("returns a tamagotchi by its id number") do test_tamagotchi = Tamagotchi.new("lil dragon") test_tamagotchi.save() test_tamagotchi2 = Tamagotchi.new("big dragon") test_tamagotchi2.save() expect(Tamagotchi.find(test_tamagotchi.id())).to(eq(test_tamagotchi)) end end describe("#id") do it("returns the id of the tamagotchi") do test_tamagotchi = Tamagotchi.new("lil dragon") test_tamagotchi.save() expect(test_tamagotchi.id()).to(eq(1)) end end end
true
a88e81822ab16b30bfe81998d29e1dbd55ac63c2
Ruby
dsstewa/todo-ruby-basics-online-web-prework
/lib/ruby_basics.rb
UTF-8
272
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def division(num1, num2) n = num1 / num2 n end def assign_variable(value) n = value end def argue(hello) hello end def greeting(hello,bye) end def return_a_value n = "Nice" n end def last_evaluated_value n = "expert" n end def pizza_party(n = "cheese") n end
true
7994a0b24c987bf7525962e5fc972d423dc38c39
Ruby
nathanworden/RB101-Programming-Foundations
/RB101-RB109_small_problems/13.debugging/11.whats_wrong_with_the_output.rb
UTF-8
1,258
4.59375
5
[]
no_license
# What's wrong with the output? # Josh wants to print an array of numeric strings in reverse numerical order. # However, the output is wrong. Without removing any code, help Josh get the # expected output. # arr = ["9", "8", "7", "10", "11"] arr = ["9", "8", "7", "10", "11"] p arr.sort do |x, y| y.to_i <=> x.to_i end # Expected output: ["11", "10", "9", "8", "7"] # Actual output: ["10", "11", "7", "8", "9"] # Its the binding! # p arr.sort is binding more tightly than the block for sort. # If you open up irb and don't use p to ouput the result, you will # see that the return value of: # arr = ["9", "8", "7", "10", "11"] # arr.sort do |x, y| # y.to_i <=> x.to_i # end # is: ["11", "10", "9", "8", "7"] # BUT when you add the p back in, the return value of: # arr = ["9", "8", "7", "10", "11"] # p arr.sort do |x, y| # y.to_i <=> x.to_i # end # is: ["10", "11", "7", "8", "9"] # If you just run arr.sort, you get ["10", "11", "7", "8", "9"], # so p arr.sort is what is being printed out because p is binding # more tightly to arr.sort than the block after sort is. # You can solve this by giving parenthesis to arr.sort, like this: arr = ["9", "8", "7", "10", "11"] p (arr.sort do |x, y| y.to_i <=> x.to_i end)
true
23694dea8e1e0c60d9066f9c52e7f7e9e73e0c35
Ruby
johnram528/ufc-rankings-cli-gem
/lib/ufc_rankings/rankings.rb
UTF-8
877
2.84375
3
[ "MIT" ]
permissive
class UfcRankings::Rankings @@division_names = ["Pound for Pound", "Flyweight", "Bantamweight", "Featherweight", "Lightweight", "Welterweight", "Middleweight", "Light Heavyweight", "Heavyweight", "Women's Strawweight", "Women's Bantamweight"] @@divisions = {} @@division_names.each_index {|i| @@divisions[i] = Array.new} def self.scrape_rankings doc = Nokogiri::HTML(open("http://www.ufc.com/rankings")) rankings = doc.css(".ranking-list") @@division_names.each_index {|i| rankings[i].css("a").children.each {|fighter| @@divisions[i] << fighter.text.strip.split.join(" ")}} create_fighters end def self.create_fighters @@divisions.each {|k, v| v.each_with_index {|name,ranking| fighter = UfcRankings::Fighters.new(name, k, ranking)}} end def self.divisions @@divisions end def self.division_names @@division_names end end
true
cbc0d2f1eed3525f683b9b2f21272caf20f72e73
Ruby
quantumduck/stretch_tdd_ruby
/stretch_05_array_extensions/array_extensions.rb
UTF-8
151
3.3125
3
[]
no_license
class Array def sum total = 0 each { |element| total += element } total end def square map { |element| element**2 } end end
true
4ef0eb60f308b67675bce422d5947d7b0b9f4bd6
Ruby
axionos/silicon-valley-code-challenge-nyc-web-career-040119
/app/models/venture_capitalist.rb
UTF-8
1,061
2.921875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class VentureCapitalist attr_reader :name, :total_worth @@all = [] def initialize(name, total_worth) @name = name @total_worth = total_worth @@all << self end # INSTANCE METHODS def offer_contract(startup, type, investment) FundingRound.new(startup, self, type, investment) end def all_funding_rounds_for_vc FundingRound.all.select do |fr| fr.venture_capitalist.name == self.name end end def funding_rounds all_funding_rounds_for_vc end def portfolio all_funding_rounds_for_vc.map do |fr| fr.startup end.uniq end def biggest_investment all_funding_rounds_for_vc.map do |fr| fr.investment end.max end def invested(domain) FundingRound.all.select do |fr| if fr.startup.domain == domain fr.investment end end.map do |investments| investments.investment end.sum end # CLASS METHODS def self.all @@all end def self.tres_commas_club self.all.select do |vc| vc.total_worth > 1000000000 end end end
true
1675468415870986baae2413a7ec63c0d1e100fa
Ruby
cielavenir/procon
/atcoder/tyama_atcodernikkei2019exG.rb
UTF-8
134
3.015625
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby h=Hash.new 0 gets.chomp.chars{|c|h[c]+=1} x=y=0 h.each_value{|v|d,r=v.divmod 2;x+=d*2;y+=r} y>0&&(y-=1;x+=1) p x**2+y
true
3bd0a07262ae990509e3001a8fe8a393393e8c1a
Ruby
guns/haus
/lib/ruby/nerv/util/notification.rb
UTF-8
3,212
2.515625
3
[ "MIT" ]
permissive
# -*- encoding: utf-8 -*- # # Copyright (c) 2011-2017 Sung Pae <self@sungpae.com> # Distributed under the MIT license. # http://www.opensource.org/licenses/mit-license.php require 'cgi' module NERV; end module NERV::Util; end class NERV::Util::Notification PRESETS = { 'alert' => { :title => nil, :message => 'Attention', :audio => File.expand_path('~/.local/share/sounds/alert.ogg'), :icon => nil, :sticky => false, }, 'warning' => { :title => 'Warning', :message => nil, :audio => File.expand_path('~/.local/share/sounds/warning.ogg'), :icon => 'dialog-warning', :sticky => false, }, 'success' => { :title => 'Success', :message => nil, :audio => File.expand_path('~/.local/share/sounds/success.ogg'), :icon => 'dialog-ok', :sticky => false, }, 'error' => { :title => 'Error', :message => nil, :audio => File.expand_path('~/.local/share/sounds/error.ogg'), :icon => 'dialog-error', :sticky => false, }, 'new-mail' => { :title => 'New mail', :message => nil, :audio => File.expand_path('~/.local/share/sounds/new-mail.ogg'), :icon => 'mail', :sticky => false, }, 'battery-low' => { :title => 'Caution', :message => 'Battery low', :audio => File.expand_path('~/.local/share/sounds/battery-low.ogg'), :icon => 'battery-caution', :sticky => false, } } attr_accessor :message, :title, :sticky, :audio, :icon def initialize opts = {} @audio = :voice apply_preset opts[:preset] if opts[:preset] @title = opts[:title] if opts.has_key? :title @message = opts[:message] if opts.has_key? :message @sticky = opts[:sticky] if opts.has_key? :sticky @audio = opts[:audio] if opts.has_key? :audio @icon = opts[:icon] if opts.has_key? :icon end def apply_preset key preset = PRESETS[key] @title = preset[:title] @message = preset[:message] @audio = preset[:audio] @icon = preset[:icon] @sticky = preset[:sticky] end def have cmd system %Q(/bin/sh -c 'command -v #{cmd}' >/dev/null 2>&1) end def forkexec *args Process.detach fork { [$stdout, $stderr].each { |fd| fd.reopen '/dev/null' } exec *args } end def notify if have 'notify-send' cmd = %W[notify-send] cmd << '--urgency=critical' if sticky cmd << "--icon=#{icon}" if icon cmd << title if title and not title.empty? cmd << CGI.escape_html(message.to_s) forkexec *cmd elsif have 'growlnotify' cmd = %W[growlnotify -m #{message}] cmd += %W[--title #{title}] if title cmd << '--sticky' if sticky forkexec *cmd end end def play return unless audio if audio == :voice if have 'espeak' forkexec 'espeak', message end elsif File.readable? audio if have 'play' forkexec 'play', '-q', audio end end end def call pool = [] %w[play notify].each do |m| pool << Thread.new { send m } end pool.each &:join end end
true
9a48eff1ab9aac9aef10bbc3b019603a88998371
Ruby
diegodurs/checklist
/lib/checklist/list.rb
UTF-8
2,121
3.015625
3
[]
no_license
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' module Checklist class List extend ::Forwardable def_delegators :@list, :each, :map, :select, :first, :last attr_reader :items, :context def initialize(klass, &block) @klass, @items = klass, [] update(&block) end def update(&block) instance_eval(&block) if block_given? self end # return true if all items are validated def valid? items.each do |item| return false unless item.checked? end return true end def context= (instance) @context = instance end # = Example # each_checked do |explain, checked| # puts "#{explain} = #{checked}" # end def each_checked(options = {}, &block) options = parse_options(options) get_items(options).each do |item| block.call(item.explain, item.checked?) end end def map_checked(options = {}, &block) options = parse_options(options) block ||= lambda { |msg, checked| [msg, checked] } items.map {|item| block.call(item.explain, item.checked?) } end def errors items.select { |item| !item.checked? } end # items that should be checked def filtered_items items.select { |item| item.keep? } end private def check(explain, item_options = {}, &block) @items << Item.new(explain, self, item_options, &block) end def get_items(options) options[:filtered] ? filtered_items : items end def default_options { filtered: true } end def parse_options(options = {}) default_options.merge(options) end end end
true
088884cd59cc107a8649832addfdcd5f4704347f
Ruby
MASisserson/rb101
/small_problems/easy_6/7.rb
UTF-8
1,527
4.21875
4
[]
no_license
# Halvsies =begin PEDAC Input: array Output: 1 nested array Requirements: Splits down the middle favor the first half Elements and arrays in same order as original array. Nondestructive Returns 2 arrays even if one or both would be empty Mental Model: Make one array that is the second cut, using negative size halved. Make a second array that is the first cut of the remainder. Join the two as arrays using each or something. Cut the arrays by transplanting size / 2 times. Takes advantage of 0 start. Algorithm: index = 0 array_1 array_2 (origin.size / 2).times do array_1 << origin[index] index += 1 end until index = origin.size do array_2 << origin[index] index += 1 end join the two arrays =end # def halvsies(origin) # case origin.size.odd? # when true then cut = (origin.size / 2) # when false then cut = (origin.size / 2) - 1 # end # array_1 = [] # for i in 0..cut # array_1 << origin[i] # end # array_2 = [] # for i in (cut + 1)..(origin.size - 1) # array_2 << origin[i] # end # final = [] # final[0], final[1] = array_1, array_2 # end def halvsies(array) middle = (array.size / 2.0).ceil first_half = array.slice(0, middle) second_half = array.slice(middle, array.size - middle) [first_half, second_half] end p halvsies([1, 2, 3, 4]) == [[1, 2], [3, 4]] p halvsies([1, 5, 2, 4, 3]) == [[1, 5, 2], [4, 3]] p halvsies([5]) == [[5], []] p halvsies([]) == [[], []]
true
5147d5cffbdd0c3d5093ea839c20ed9f0dacbdca
Ruby
eosin-kramos/Ruby-Exercises-
/picky_eater.rb
UTF-8
532
3.4375
3
[ "MIT" ]
permissive
foods = ["Candy", "Soda", "Lettuce", "McDonalds", "KFC", "Mango", "Carrot"] vegetables = ["Lettuce", "Broccoli", "Carrot", "Onion"] fruits = ["Apple", "Orange", "Mango", "Pineapple"] foods.each do |food| if vegetables.include?(food) 4.times do puts "Gross, I hate #{food}" end elsif fruits.include?(food) puts "How about we a make a smoothie with #{food}" else puts "Om nom nom... I love #{food}" end end puts "Enter a food to feed me:" user_food = gets.chomp puts "Om nom nom... I love #{user_food}"
true
f11dc7a4561b3c2d34124056d3564be8825e0539
Ruby
21sapphire/IntroBook
/1Basics/Ex1.rb
UTF-8
675
3.90625
4
[]
no_license
# 1 puts "Matthew " + "Buckman" # 2 puts 5678 / 1000 puts 5678 % 1000 / 100 puts 5678 % 1000 % 100 / 10 puts 5678 % 1000 % 100 % 10 # 3 movies = {:jurassic_park => 1993, :et => 1982, :minority_report => 2002, :bridge_of_spies => 2015} puts movies[:jurassic_park] puts movies[:et] puts movies[:minority_report] puts movies[:bridge_of_spies] # 4 date_movies = [1993, 1982, 2002, 2015] puts date_movies[0] puts date_movies[1] puts date_movies[2] puts date_movies[3] # 5 puts 5*4*3*2*1 puts 6*5*4*3*2*1 puts 7*6*5*4*3*2*1 puts 8*7*6*5*4*3*2*1 # 6 puts 6.5*6.5 puts 7.567*7.567 puts 3.22*3.22 # 7 # On line 2, a closing parenthesis was used instead of a closing curly brace.
true
e260f6ccc7a8380af49639c259e149eeae8e01db
Ruby
tsukajizo/bingo
/testBingo.rb
UTF-8
415
3.234375
3
[]
no_license
require_relative "bingo" bingo = Bingo.new while bingo.remain? bingo.select_number print bingo.current_number print "\n" end print Bingo::MESSAGE_GAME_IS_OVER bingo = Bingo.new 35.times{|n| bingo.select_number} print bingo.used_numbers[4] print ":" print bingo.unused? bingo.used_numbers[4] print "\n" print bingo.remaining_numbers[4] print ":" print bingo.unused? bingo.remaining_numbers[4] print "\n"
true
a76888f0b2ce041277f578061ed024935af6bfdf
Ruby
idoo/simple_shop
/spec/shop_spec.rb
UTF-8
659
2.53125
3
[]
no_license
require 'spec_helper' # require_relative 'shop/pricing_rules' # require_relative 'shop/checkout' describe 'Shop' do let(:co) { Shop::Checkout.new(Shop::PRICING_RULES) } let(:items1) { ['FR1', 'AP1', 'FR1', 'CF1'] } let(:items2) { ['FR1', 'FR1'] } let(:items3) { ['AP1', 'AP1', 'FR1', 'AP1'] } it 'should calculate correct' do items1.each { |item| co.scan(item) } expect(co.total).to eql(19.34) end it 'should calculate correct' do items2.each { |item| co.scan(item) } expect(co.total).to eql(3.11) end it 'should calculate correct' do items3.each { |item| co.scan(item) } expect(co.total).to eql(16.61) end end
true
ed4e25f4a0e968b8aa33ee8ee880885bba279237
Ruby
matipan/odin_ruby
/project_recursion/merge.rb
UTF-8
491
3.5
4
[]
no_license
require 'benchmark/ips' def merge_sort(array) return array if array.length <= 1 half = array.length / 2 merge_arrays(merge_sort(array[0..half-1]),merge_sort(array[half..-1])) end def merge_arrays(left, right) sorted = [] until left.empty? or right.empty? left.first <= right.first ? sorted << left.shift : sorted << right.shift end sorted + left + right end array = (0..50000).to_a.shuffle Benchmark.ips do |bm| bm.report("50000 elements") do merge_sort(array) end end
true
3dfa7c53fabf5fb3930c5f189e8b0bc0fba32356
Ruby
shvets/misc-ruby
/image-resizer/image-resizer.rb
UTF-8
1,167
3.421875
3
[]
no_license
# idea from here: http://railstech.com/2011/02/resize-image-using-gd2/ require 'rubygems' require "image_size" require "open-uri" require 'gd2-ffij' class ImageResizer include GD2 def resize input_name, output_name, resized_width = 100, resized_height = 100 image = Image.import(input_name) resize_image = image.resize(resized_width, resized_height, true) resize_image.export(output_name, {}) end def resize_with_ratio input_name, output_name, ratio image_size = imagesize input_name resized_width = image_size.width/ratio.to_i resized_height = image_size.height/ratio.to_i image = Image.import(input_name) resize_image = image.resize(resized_width, resized_height, true) resize_image.export(output_name, {}) end private def imagesize file_name open(file_name, "rb") do |f| ImageSize.new(f.read) end end end resizer = ImageResizer.new if ARGV.size == 4 resizer.resize(*ARGV) elsif ARGV.size == 3 resizer.resize_with_ratio(*ARGV) elsif ARGV.size < 3 puts "Not enough parameters. Use 'ruby image-resizer.rb infile outfile width height'" else end
true
3380838819d1e1a95e694cc88c903ac75826c91d
Ruby
jsonjordan/Blackjack_2
/player.rb
UTF-8
399
3.28125
3
[]
no_license
require './hand' class Player attr_reader :wallet, :hand def initialize wallet = 0 @wallet = wallet hand_new end def add_to_hand card @hand.add(card) end def wins ammount @wallet += ammount end def broke? wallet == 0 end def hand_new @hand = Hand.new end def hit? puts "Would you like to (h)it or (s)tay?" gets.chomp == "h" end end
true
2c98428f1a11bf98f92d6a99fcbf46211ced9915
Ruby
yuji91/RefactoringRuby_01_sample
/main.rb
UTF-8
336
2.703125
3
[]
no_license
require './movie.rb' require './rental.rb' require './customer.rb' require './regular_price' require './new_release_price' require './children_price' movie = Movie.new("movie_01", Movie::REGULAR) rental = Rental.new(movie, 0) customer = Customer.new("customer_01") customer.add_rental(rental) result = customer.statement puts result
true
12c788db4aa51294cd453bd868d1808a9889ef2c
Ruby
mikefieldmay/tech_test_bank
/spec/statement_printer_spec.rb
UTF-8
1,371
2.78125
3
[]
no_license
require 'statement_printer' describe StatementPrinter do let(:transaction){ Struct.new("Transaction", :date, :credit, :debit, :balance )} let(:transaction_one) { transaction.new( '14/01/2012', '', '500.00', '2500.00' ) } let(:transaction_two) { transaction.new( '13/01/2012', '2000.00', '', '3000.00' ) } let(:transaction_three) { transaction.new( '10/01/2012', '1000.00', '', '1000.00' ) } let(:transaction_log) {double :transaction_log, transactions: [transaction_one, transaction_two, transaction_three] } describe "#show" do it 'prints out the transactions of an account' do printed_statement = ["date || credit || debit || balance", "14/01/2012 || || 500.00|| 2500.00", "13/01/2012 || 2000.00|| || 3000.00", "10/01/2012 || 1000.00|| || 1000.00\n"].join("\n") expect(STDOUT).to receive(:puts).with(printed_statement) StatementPrinter.show(transaction_log) end end end
true
568d1f3e2f5d18fc1654d5fdc566caf66d707bee
Ruby
meinside/meinside-ruby
/lib/externals.rb
UTF-8
2,995
2.59375
3
[ "BSD-3-Clause" ]
permissive
# coding: UTF-8 # lib/externals.rb # # functions using external services # (in unofficial ways) # # created on : 2013.02.27 # last update: 2013.08.23 # # by meinside@gmail.com require 'json' require_relative 'my_http' require_relative 'my_str' module Externals FAKE_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.99 Safari/537.22" class Naver # auto-space given text with naver lab's web interface # (http://s.lab.naver.com/autospacing/) def self.autospace(str) result = MyHttp.post("http://s.lab.naver.com/autospacing/", {query: str,}) if result.code.to_i == 200 if result.body =~ /\<div class=\"wrap_spacing2\" style=\"clear:both;\"\>\s*\<p\>(.*?)\<\/p\>\s*\<\/div\>/im return $1.strip_tags end end return nil rescue puts "# exception in autospace: #{$!}" return nil end end class Google # return locale of given string suggested by google translate's web interface def self.detect_language(str) result = MyHttp.get("http://translate.google.com/translate_a/t", {client: "t", text: str, hl: "en", sl: "auto", tl: "auto", ie: "UTF-8", oe: "UTF-8"}, {"User-Agent" => FAKE_USER_AGENT,}) if result.code.to_i == 200 if result.body =~ /\[\[\[.*?\]\],(.*)"/ txt = $1 while txt =~ /\[[^\[\]]*\]/ txt = txt.gsub(/\[[^\[\]]*\]/, "") end return $1.strip if txt =~ /^,\"([a-z]+)\"/i end end return nil rescue puts "# exception in detect_language: #{$!}" return nil end # translate given string with google translate's web interface def self.translate(str, from_lang, to_lang) result = MyHttp.get("http://translate.google.com/translate_a/t", {client: "t", text: str, hl: "en", sl: from_lang, tl: to_lang, ie: "UTF-8", oe: "UTF-8", multires: 1, otf: 1, pc: 1, ssel: 4, tsel: 0, sc: 1}, {"User-Agent" => FAKE_USER_AGENT,}) if result.code.to_i == 200 if result.body =~ /\[\[(\[.*?\])\]/ return JSON.parse($1.strip, {allow_nan: true})[0] end end return nil rescue puts "# exception in translate: #{$!}" return nil end # download translated text's sound file # (http://translate.google.com/translate_tts?tl=ko&q=What+the+hell) def self.text_to_soundfile(str, to_lang, out_filepath) result = MyHttp.get("http://translate.google.com/translate_tts", {tl: to_lang, q: str,}, {"User-Agent" => FAKE_USER_AGENT,}) if result.code.to_i == 200 File.open(out_filepath, "wb"){|file| file << result.body} return true else return false end rescue puts "# exception in text_to_soundfile: #{$!}" return false end end end
true
9dad5500edbcc5c82ea4de98d9e55f9e9f8af64f
Ruby
heptagon-inc/adwords
/cities.rb
UTF-8
572
2.578125
3
[]
no_license
#!/usr/bin/env ruby # coding: utf-8 @cities = %w( 青森市 弘前市 八戸市 黒石市 五所川原市 十和田市 三沢市 むつ市 つがる市 平川市 平内町 今別町 蓬田村 外ヶ浜町 鰺ヶ沢町 深浦町 西目屋村 藤崎町 大鰐町 田舎館村 板柳町 鶴田町 中泊町 野辺地町 七戸町 六戸町 横浜町 東北町 六ヶ所村 おいらせ町 大間町 東通村 風間浦村 佐井村 三戸町 五戸町 田子町 南部町 階上町 新郷村 )
true
adcbba81887f1042c7899f47ae9b6fd33280958f
Ruby
BaptisteCoulon/Project-ruby
/Game.rb
UTF-8
1,568
2.796875
3
[]
no_license
require 'gosu' require_relative "./Joueur.rb" require_relative "./Map.rb" require_relative "./Tiles.rb" require_relative "./Rectangle.rb" require_relative "./Ennemi.rb" require_relative "./Cheese.rb" require_relative "./State.rb" require_relative "./GameState.rb" require_relative "./MenuState.rb" require_relative "./OptionState.rb" require_relative "./Button.rb" #require_relative "./coin.rb" #require_relative "./terre.rb" include Gosu $game = nil class Game < Gosu::Window attr_accessor :joueur, :ms_left_pressed # On initialize la fenetre attr_accessor :current_State def initialize super 1280,720,false # On donne un titre a notre fenetre self.caption = "Mon Petit Corbeau" $game = self @current_State = :menu @states = { menu:MenuState.new(self), options:OptionState.new(self), game:GameState.new(self) } @game_State = GameState.new(self) @ms_left_pressed = false #@song = Song.new("Sons/Sound.mp3") #@coin_song = Sample.new("Assets/coins-in-hand-4.wav") end #afficher def update @states[@current_State].update @ms_left_pressed = false end def draw @states[@current_State].draw end def needs_cursor? if @current_State.is_a? MenuState return true else return true end end def button_down(id) super(id) if id== MS_LEFT @ms_left_pressed = true end end def current_State=(value) @current_State = value @states[@current_State].reset end end Game.new.show()
true
1b5000ac0c3317f9b656b4ac6a5ce68b55135491
Ruby
v-yarotsky/taketo
/lib/taketo/config_traverser.rb
UTF-8
473
2.6875
3
[ "MIT" ]
permissive
require 'delegate' require 'forwardable' module Taketo class ConfigTraverser def initialize(root) @root = root end def visit_depth_first(visitor) path_stack = [@root] while path_stack.any? node = path_stack.pop visitor.visit(node) node.class.node_types.each do |node_type| node.nodes(node_type).reverse_each do |n| path_stack.push(n) end end end end end end
true
a6ecee1db6c4ef11e1a66fdba84f884ec8e94cfe
Ruby
lcloyola/upis-ror
/app/models/gwa.rb
UTF-8
1,945
2.75
3
[]
no_license
class Gwa < ActiveRecord::Base belongs_to :student belongs_to :schoolyear def self.search(schoolyear, batch, mode) gwas = Gwa.joins(:student) gwas = gwas.where('students.batch_id' => batch.id, 'schoolyear_id' => schoolyear.id, 'gwa_type' => mode) gwas = gwas.each{|s| s[:deficiency] = s.student.has_deficiency?(schoolyear, mode - 1)} return gwas.each{|s| s[:failing] = s.student.has_failing?(schoolyear, 0)} end # refactor? computation involves 1 controller and 3 models >.< def recompute # get involved courses if self.gwa_type == GwaMode::Cumulative courses = self.student.courses else courses = self.student.courses_year(self.schoolyear_id) end sem = self.gwa_type - 1 # 1st sem and 2nd sem cases sem = 0 if self.gwa_type == GwaMode::Schoolyear || self.gwa_type == GwaMode::Cumulative self.raw = Gwa.gwa_raw(courses, self.student, sem) self.final = Gwa.gwa_final(courses, self.student, sem) self.save end # this is not valid for semestral case. def self.gwa_final(courses, student, sem) total = units = 0 courses.each do |c| if sem == 0 final = c.student_final(student.id) final = student.course_removal_grade(c) if student.course_removed(c).present? else # semestral case final = c.student_sem_final(student.id, sem) end total = (final * c.subject.units) + total units = c.subject.units + units end return (total / units).round(5) if units != 0 return "" end def self.gwa_raw(courses, student, sem) total = units = 0 courses.each do |c| if sem == 0 raw = c.student_average(student.id) else # semestral case raw = c.student_sem_average(student.id, sem) end unless raw == 0 total = (raw * c.subject.units) + total units = c.subject.units + units end end return (total / units).round(5) if units != 0 return "" end end
true
4a6cf95037c79ce15ffb928c3a2e92b9d1d2f8f6
Ruby
limeiralucas/LocadoraRuby
/Item.rb
UTF-8
383
3.390625
3
[]
no_license
class Item attr_reader :name, :id, :year, :genre, :avaliable def initialize(id, name, year, genre) @id = id @name = name @year = year @genre = genre @avaliable = true end def to_s() "Item ##{id}\n Name: #{name}\n Year: #{year}\n Avaliable: #{avaliable ? "Yes" : "No" }\n" end def lease() @avaliable = false end def unlease() @avaliable = true end end
true
53b08fdb867e61b223877feabbd54fdbb3e20cfd
Ruby
AlexandreDutra-Dev/Curso-Ruby-Rails
/ruby_language/numbers.rb
UTF-8
1,243
4.03125
4
[]
no_license
=begin Open Shell In Repl.it shift + cmd + p type shell, hit enter Methods object.odd? object.even? =end puts "\nNumbers\n" puts 1 + 2 puts 5 + 6 puts 10 * 2 puts 10 / 2 puts 10 / 4 # Integer of division drops decimal puts 10.0 / 4 # converts puts 10 / 4.to_f # method converts puts (10 / 4).to_f # Evaluates the paratheses first, then converts puts "\nVariables\n" x = 5 y = 10 puts y / x puts "" # puts "5" * "5" # Error puts "5" * 2 # Concatenation # puts 2 * "5" # Can not multipy by a string puts "I am a line" puts "-" * 20 puts "I am a differnt line after a divider" 20.times { print "-" } # dDes action x times 20.times { puts rand(10) } 20.times { puts rand(100) } # rand generates random number puts "" x = "5".to_i puts x puts x.to_f y = "10".to_f puts x * y puts "hello".to_i puts "hello".to_f x = "hello" puts x puts x.to_i # Returns 0 when it can not convert puts "\nSimple Calculator\n" 20.times { print "-" } puts "\nEnter first number" num_1 = gets.chomp # Good idea to keep raw data puts "Enter second number" num_2 = gets.chomp puts "The first number multiplied by the second number is #{num_1.to_i * num_2.to_i}" puts "\nHW 2 Simple Calculator" puts "Addition, Subtraction, Multiply, Division, Mod"
true
632ea04fc3cda5361ce8395998500322577703bc
Ruby
FiddlersCode/kata
/CamelCaseMethod/lib/CamelCaseMethod.rb
UTF-8
111
3.21875
3
[]
no_license
def CamelCaseMethod(string) string.split.map(&:capitalize).join end puts CamelCaseMethod("bob the builder")
true
fbef7af13fc829fb52c131f29f10216daf2c9c55
Ruby
bitterfly/bikesurfing
/src/bikesurf/lib/bikesurf/helpers/date_helper.rb
UTF-8
754
2.71875
3
[]
no_license
require 'date' module Bikesurf module Helpers module DateHelper def timestamp_to_date(timestamp) return nil unless timestamp Time.at(timestamp).utc.to_datetime.to_date end def date_to_timestamp(date) return nil unless date Time.utc(date.year, date.month, date.day).to_i end def timestamp_to_time(timestamp) return nil unless timestamp Time.at(timestamp).utc end def time_to_timestamp(time) return nil unless time time.to_time.to_i end def valid_period?(from, to) from <= to end def day_difference(from, to) # smarter implementation needed (to - from).to_i + 1 end end end end
true
af94c2718186e67918d285d9e4b7fffafa07d2f6
Ruby
petrachi/hydrogen
/lib/hydrogen/seeder.rb
UTF-8
371
2.59375
3
[ "MIT" ]
permissive
class Hydrogen::Seeder attr_accessor :update, :reset def initialize update: false, reset: false @update = update @reset = reset end def seed stocks.map &:seed end def stocks Dir[File.join(Rails.root, "db", "hydrogen", "*")] .select{ |file| File.directory? file } .map{ |file| Hydrogen::Stock.new file, seeder: self } end end
true
3035ade4864a58d9d9a92d1c0ef709af741b6ebf
Ruby
innku/dashboard
/lib/sharewall_client.rb
UTF-8
469
2.71875
3
[]
no_license
require 'rest_client' require 'json' class SharewallClient attr_accessor :url def initialize url @url = url end def execute raw_response = RestClient.get(url) @response = JSON.parse(raw_response.body).reverse[0..7] end def data if @response @response.map do |link| { body: link['title'], name: link['user']['name'], avatar: link['user']['image_url'] } end end end end
true
58e5e0c26b93e37b95409f9279a05296b30d38a4
Ruby
mb-mysterdev/ruby_exo
/exo_13.rb
UTF-8
143
2.859375
3
[]
no_license
puts "Votre année de naissance svp ??" année_de_naissance = gets.to_i i = année_de_naissance begin puts(i) i +=1; end until i > 2018
true
b97c46088a6cdd00e6372272f580b468a3fdd318
Ruby
binoymichael/exercism-solutions
/ruby/hamming/hamming.rb
UTF-8
345
3.171875
3
[]
no_license
module BookKeeping VERSION = 3 end class Hamming def self.compute(first_strand, second_strand) throw ArgumentError unless first_strand.length == second_strand.length return 0 if first_strand == second_strand return (0...first_strand.length).count do |index| first_strand[index] != second_strand[index] end end end
true
09b06760f139b340f7783b1176fcf30852190418
Ruby
ddugue/garden-rake
/test/args.rb
UTF-8
2,853
2.53125
3
[ "MIT" ]
permissive
require 'rake/garden/command_args' require 'rake/garden/commands/sh' require 'rake/garden/context' require 'rake/garden/filepath' require_relative 'fake_manager' RSpec.describe Garden::CommandArgs, "#initialize" do it "should create an arg based on a string" do expect("a" >> "b").to eq(["a", "b"]) end it "should create an arg based on multiple strings" do expect("a" >> "b" >> "c").to eq(["a", "b", "c"]) end it "should create an arg with arrays" do expect(["a", "d"] >> "b" >> "c").to eq([["a", "d"], "b", "c"]) end it "should create an arg with arrays" do expect(["a", "d"] >> ["b", "c"] >> "d").to eq([["a", "d"], ["b", "c"], 'd']) end it "Should work with a filepath" do expect(Garden::Filepath.new("c") >> "b").to eq(["c", 'b']) end end RSpec.describe Garden::ShArgs do context "with all args" do subject { Garden::ShArgs.new(nil, ["a.txt", "%b.txt"], "cmd %f", ["c.txt"]) } it "should work with no context" do subject.validate expect(subject.input).to eq(["a.txt", "%b.txt"]) expect(subject.command).to eq("cmd %f") expect(subject.output).to eq(["c.txt"]) end it "should work with file context" do Garden::Context.instance.with_value :file, Garden::Filepath.new("c.rb") do subject.validate expect(subject.command).to eq("cmd c.rb") expect(subject.output).to eq(["c.txt"]) expect(subject.input).to eq(["a.txt", "c.txt"]) end end end end RSpec.describe Garden::ShCommand do context 'with arguments' do subject { Garden::ShCommand.new(FakeManager.new, *args) } describe 'with only command' do let(:args) { 'cmd' } it { is_expected.to have_attributes('command' => 'cmd') } end describe 'with output and command' do let(:args) { 'cmd' >> 'output.txt' } it { is_expected.to have_attributes('command' => 'cmd') } it "should have rigth input" do expect(subject.instance_variable_get(:@args).output).to eq('output.txt') end end describe 'with input and command and output' do let(:args) { 'input.txt' >> 'cmd' >> 'output.txt' } it { is_expected.to have_attributes('command' => 'cmd') } it "should have rigth input" do expect(subject.instance_variable_get(:@args).input).to eq('input.txt') expect(subject.instance_variable_get(:@args).output).to eq('output.txt') end end describe 'with inputs, output and command' do let(:args) { ['input.txt', 'input2.txt'] >> 'cmd' >> 'output.txt' } it { is_expected.to have_attributes('command' => 'cmd') } it "should have rigth input" do expect(subject.instance_variable_get(:@args).input).to eq(['input.txt', 'input2.txt']) expect(subject.instance_variable_get(:@args).output).to eq('output.txt') end end end end
true
794df2b4643b60e8ae4ba1a3c1330ee33123e94e
Ruby
sreeharikmarar/geektrust-cricket
/cricket_2/lib/cricket/team.rb
UTF-8
1,915
3.15625
3
[]
no_license
require 'yaml' module Cricket class Team attr_reader :name, :players, :score_board attr_accessor :striker, :non_striker def initialize(name) @name = name initialize_team end def striker_play(ball) run = @striker.play(ball) update_score(ball, run) end def game_ends? @score_board.game_ends? end def player_gets_out? @striker.gets_out? && next_players.any? end def change_player change_striker if @striker.gets_out? end def change_striker @striker = next_players.first @striker.batting! end def set_target(runs) @score_board.set_target(runs + 1) end def set_overs(num_of_overs) @score_board.set_overs(num_of_overs) end def update_overs @score_board.update_overs rotate_strikers end def update_score(ball, runs) @score_board.update(ball, runs, @striker) update_strike(runs) @score_board.display_coverage(ball) end def update_strike(runs) rotate_strikers if @striker.should_rotate?(runs) change_player if player_gets_out? end def total @score_board.runs end def wins? @score_board.wins? end private def initialize_team initialize_players initialize_score_board end def initialize_players @players = get_players @striker, @non_striker = @players[0..1] @striker.batting! @non_striker.batting! end def get_players squad = Cricket::Squad.new(@name, YAML.load_file("#{Cricket.data}/yaml/team_squad.yml")) squad.players end def initialize_score_board @score_board = ScoreBoard.new(@name, @players) end def next_players @players.select { |player| player.yet_to_bat } end def rotate_strikers @striker, @non_striker = @non_striker, @striker end end end
true
be92421f263961c7a91abf0f5a20c31ea6948153
Ruby
drLoom/csv_to_ascii
/test/test_parser.rb
UTF-8
382
2.609375
3
[]
no_license
require "minitest/autorun" require 'lib/parser' class TestParser < Minitest::Test def test_it_should_leave_value_same text = <<~TEXT int;string;money; 1;aaa bbb ccc;1000.33 TEXT assert_equal [[ { type: "int", value: "1" }, { type: "string", value: "aaa bbb ccc" }, { type: "money", value: "1000.33" }]], Parser.new.parse(text) end end
true
288abce41ddca0f3cdff2c2200ea412389befb56
Ruby
jcovell/lesson2
/rubocop.rb
UTF-8
1,436
3.53125
4
[]
no_license
=begin Rubocop is a static code analyzer. This means that it analyzes your code and offers advice regarding its style format as well as possible logical errors. In Rubocop parlance, these rules are called cops. Cops are further grouped into departments. The first department we care about is centered around enforcing good coding style. In general, Rubyists have standardized on a set of conventions. These conventions are captured into a document called the Ruby Style Guide. The style cops in Rubocop enforce the styles documented in that guide. For example, if your code isn't indented with 2 spaces, the IndentationWidth cop will complain. Code Linting The other department we're interested in is around code linting. A code linter is a program that inspects your code for possible logical errors or code smells. This isn't foolproof, but can serve as a first level of defense against obvious problems. Rubocop has some basic code linting functionality built-in. For example, if your code instantiates an unused local variable, the UselessAssignment cop will complain. Installation and Usage Rubocop is a gem, so you install it like any other gem. $ gem install rubocop Once the gem is installed, you'll have a rubocop command available from the command line. This command takes a Ruby file as an argument. For example, if you have a Ruby file called test.rb, you can run Rubocop on this file by: $ rubocop test.rb =end
true
9ba01d396a8355b6ca90fd2a175540c9a8220543
Ruby
Danarvelini/Bootcamp_Impulso--Fullstack_developer
/LearningRuby/symbols.rb
UTF-8
346
2.9375
3
[]
no_license
#Its a special type of object. They are create with ":" in the beginning of the identifier #They are immutable #Great to substitute Strings for labels and keys and hash name = 'Dan' p name.object_id #Its different every time it is set :"Dan" p :Dan.object_id #its always the same id on memory, and that makes it very useful for identifications
true
dfd54b7ba636f4c980bbc8a99f58d3aefc87a30a
Ruby
HarrisJT/css-class-string
/spec/css_class_string/helper_spec.rb
UTF-8
1,855
2.796875
3
[ "MIT" ]
permissive
require 'spec_helper' require 'css_class_string/view_helpers' describe "CssClassString::Helper" do describe ".to_s" do context "when a key's value is truthy" do let(:hash) { {truthy: true} } subject { CssClassString::Helper.new(hash).to_s } it { is_expected.to eq("truthy") } end context "when a key's value is falsy" do let(:hash) { {falsy: false} } subject { CssClassString::Helper.new(hash).to_s } it { is_expected.to eq("") } end context "when a key is an array of two elements" do context "when value is truthy" do let(:hash) { {[:truthy, :falsy] => true} } subject { CssClassString::Helper.new(hash).to_s } it { is_expected.to eq("truthy") } end context "when value is falsy" do let(:hash) { {[:truthy, :falsy] => false} } subject { CssClassString::Helper.new(hash).to_s } it { is_expected.to eq("falsy") } end end context 'when multiple keys are given' do let(:hash) { { [:arr_truthy, :arr_falsy] => false, :str_truthy => true, :str_falsy => false } } subject { CssClassString::Helper.new(hash).to_s } it { is_expected.to match(/^\w+ \w+$/) } it { is_expected.to include('arr_falsy', 'str_truthy') } it { is_expected.not_to include('arr_truthy', 'str_falsy') } end context 'with truthy arguments only' do subject { CssClassString::Helper.new('truthy_1', 'truthy_2').to_s } it { is_expected.to eq('truthy_1 truthy_2') } end context 'with mixed arguments' do subject { CssClassString::Helper.new('truthy_1', 'truthy_2', falsy: false, truthy_3: true).to_s } it { is_expected.to eq('truthy_1 truthy_2 truthy_3') } end end end
true
874878046272eef5615f0f214d897b5f1c8758bd
Ruby
komiyak/reading-metaprogramming-ruby
/chapter_5/singleton_class.rb
UTF-8
135
3.15625
3
[]
no_license
obj = Object.new singleton_class = class << obj self end pp singleton_class pp singleton_class.class # Or pp obj.singleton_class
true
43501681475df960e41fbeb011d9b6253b043570
Ruby
itsmekhanh/leetcode
/add_two_numbers.rb
UTF-8
749
4.0625
4
[]
no_license
# you are given two linked lists representing two non-negative numbers. # The digits are stored in reverse order and each of their nodes contain a # single digit. Add the two numbers and return it as a linked list. require_relative "classes/list_node.rb" def add_two_numbers(l1, l2) head = nil tail = nil carry = 0 while !l1.nil? || !l2.nil? do sum = carry if !l1.nil? sum += l1.val end if !l2.nil? sum += l2.val end carry = if sum >= 10 then 1 else 0 end value = sum % 10 node = ListNode.new(value) if head.nil? head = node tail = node else tail.next = node tail = node end end if carry > 0 tail.next = ListNode.new(1) end return head end
true
7abc1ac4b148fca237df737fb396bde8d2aa04e7
Ruby
firechicago/advent-of-code
/Day-7-Problem-1/parse.rb
UTF-8
1,254
3.3125
3
[]
no_license
raw_data = File.readlines(ARGV[0]) def action(string) string.match(/[A-Z]+/).to_s end def receiver(string) string.chomp.match(/[a-z]+\z/).to_s end def arguments(string) string.scan(/(\d+|[a-z]+)(?= )/).flatten end class Wire @@diagram = {} attr_reader :name, :action, :arguments def initialize(name, action, arguments) @action = action @arguments = arguments @name = name @@diagram[name] = self end def self.diagram @@diagram end def value return @value if @value evaluated_arguments = arguments.map do |arg| integer?(arg) ? arg.to_i : Wire.diagram[arg].value end @value ||= case action when "" evaluated_arguments.first when "AND" evaluated_arguments.reduce(&:&) when "OR" evaluated_arguments.reduce(&:|) when "NOT" 65535 - evaluated_arguments.first when "LSHIFT" evaluated_arguments.first << evaluated_arguments.last when "RSHIFT" evaluated_arguments.first >> evaluated_arguments.last end end private def integer?(string) string.to_i.to_s == string end end wires = [] raw_data.each do |string| wires << Wire.new(receiver(string), action(string), arguments(string)) end puts Wire.diagram['a'].value
true
9b545ee76e13cf3250f041ab8c1a5c0056c6da71
Ruby
JonathanAndrews/worlds_simplest_poker
/spec/feature/configure_game_spec.rb
UTF-8
1,230
2.65625
3
[]
no_license
# frozen_string_literal: true feature 'Configure Game screen' do scenario 'displayed when entering website' do visit '/' expect(page).to have_content("Welcome the World's Simplest Poker Game") end scenario 'should have a number of players input' do visit '/' expect(page).to have_content('How many players?') end scenario 'should have a hand size input' do visit '/' expect(page).to have_content('How many cards in each hand?') end scenario 'can input 2 players with 2 cards' do visit '/' fill_in :no_of_players, with: 2 fill_in :hand_size, with: 2 end scenario 'redirected to config page if not enough cards' do visit '/' fill_in :no_of_players, with: 52 fill_in :hand_size, with: 2 click_button('Play') expect(page).to have_content("Welcome the World's Simplest Poker Game") expect(page).to have_content('How many cards in each hand?') expect(page).to have_content('How many players?') end scenario 'redirected to config page shows flash message' do visit '/' fill_in :no_of_players, with: 52 fill_in :hand_size, with: 2 click_button('Play') expect(page).to have_content('Not enough dards in the deck...') end end
true
9ef90d0a66b8b322b0adbf3a83ae39d8c63265f0
Ruby
MarkHyland/to-do-list
/lib/list.rb
UTF-8
175
2.578125
3
[]
no_license
# Have to create the class for it to show up in the # database. class List < ActiveRecord::Base has_many :items def to_s "id: #{self.id}, name: #{self.name} \n" end end
true
05b4d7e10c3ea7f8a56636a55ba23ec18923a740
Ruby
coreymartella/project_euler
/p007.rb
UTF-8
476
3.90625
4
[]
no_license
def prime(n) factors= [] return false if n % 2 == 0 3.step((n**0.5).ceil,2) do |i| return false if n % i == 0 end true end def p7(n) primes = [nil,2,3,5,7,11,13] while !primes[n] #need to fill in primes (primes.last+2..primes.last*2).step(2) do |i| primes << i if prime(i) end end primes[n] end # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number?
true
a2df554d8ab72b984572797b4fe4491e628f9d73
Ruby
vladigonzalez/Clase13
/ejercicio2.rb
UTF-8
791
3.828125
4
[]
no_license
#ejercicio2.rb puts"desarrollo 1 mostrar los productos" productos = {'bebida' => 850, 'chocolate' => 1200,'galletas' => 900, 'leche' => 750} productos.each { |producto, valor| puts "Producto: #{producto} $: #{valor}" } puts"-----------------------------------------" puts"desarrollo 2: agregar cereal 2200" puts"-----------------------------------------" productos["cereal"] = 2200 puts productos puts"-----------------------------------------" puts"desarrollo 3: cambiar valor a bedida 850 a 2000" productos["bebida"] = 2000 puts"-----------------------------------------" puts"desarrollo 4: convertir hash a array" aprod = productos.to_a print aprod puts"\n-----------------------------------------" puts"desarrollo 5: elimina galletas" productos.delete("galletas") print productos
true
f17bad2c32d7c1bb8780395fb62ecfdf4d59fff6
Ruby
SleeplessByte/RubiesInSpace
/core/generator/space.basic.rb
UTF-8
13,816
3.03125
3
[]
no_license
require_relative '../env/space.universe' module Generators module Universe ## # This is space. This is where the rubies are! # class Basic ## # # VERSION = '1.0.0' ## # Returns the size for the universe # def self.size( universe ) results = {} results[ :n ] = universe[ :size ] results[ :f ] = results[ :n ] / universe[ :connectivity ][ :faces ].to_f face_variance = results[ :f ] / 100.to_f * universe[ :variance ] results[ :f ] = ( results[ :f ] + Space::Universe.rand( face_variance ) - face_variance / 2.to_f ).round results[ :p ] = results[ :n ] + results[ :f ] - 1 return results end ## # Returns the node types for the universe # def self.contents( universe, universe_size ) results = {} results[ :stars ] = universe_size[ :n ] / universe[ :ratios ][ :stars ].to_f results[ :planets ] = universe_size[ :n ] / universe[ :ratios ][ :planets ].to_f star_variance = results[ :stars ] / 100.to_f * universe[ :variance ] planet_variance = results[ :planets ] / 100.to_f * universe[ :variance ] results[ :stars ] = ( results[ :stars ] + Space::Universe.rand( star_variance ) - star_variance / 2.to_f ).round results[ :planets ] = ( results[ :planets ] + Space::Universe.rand( planet_variance ) - planet_variance / 2.to_f ).round results[ :asteroids ] = universe_size[ :n ] - results[ :stars ] - results[ :planets ] return results end ## # Create a star # def self.create_star( nodes, universe, universe_size, universe_contents ) if universe_contents[ :stars ] <= 0 raise "I can't allow more stars in this universe." end if universe_size[ :n ] <= 0 raise "This universe is full." end universe_size[ :n ] -= 1 universe_contents[ :stars ] -= 1 result = Space::Star.new( Space::Universe.bytes Space::Universe::ENTROPY ) nodes.push result return result end ## # Create a planet # def self.create_planet( nodes, universe, universe_size, universe_contents ) if universe_contents[ :planets ] <= 0 raise "I can't allow more planets in this universe." end if universe_size[ :n ] <= 0 raise "This universe is full." end universe_size[ :n ] -= 1 universe_contents[ :planets ] -= 1 result = Space::Planet.new( Space::Universe.bytes Space::Universe::ENTROPY ) nodes.push result return result end ## # Create an asteroid # def self.create_asteroid( nodes, universe, universe_size, universe_contents ) if universe_contents[ :asteroids ] <= 0 raise "I can't allow more asteroids in this universe." end if universe_size[ :n ] <= 0 raise "This universe is full." end universe_size[ :n ] -= 1 universe_contents[ :asteroids ] -= 1 result = Space::Asteroid.new( Space::Universe.bytes Space::Universe::ENTROPY ) nodes.push result return result end ## # Create a path # def self.create_path( left, right, universe, universe_size ) if universe_size[ :p ] <= 0 raise "This universe is overly connected." end universe_size[ :p ] -= 1 result = Space::Path.new left, right, Space::Universe.rand( universe[ :distances ][ :max ] - universe[ :distances ][ :min ] ) + universe[ :distances ][ :min ] left.connect result right.connect result return result end ## # Lets make stars our cluster centers # def self.create_clusters( nodes, universe, universe_size, universe_contents ) if universe_contents[ :stars ] <= 0 raise ArgumentError "I can't create a universe that small." end clusters = [] universe_contents[ :stars ].times do clusters.push create_star( nodes, universe, universe_size, universe_contents ) end return clusters end ## # Some stars are lonely in their cluster. Let's find the cosy stars # because they will inherit all the planets, leaving the lonely star # very lonely. # def self.get_cosy_stars( nodes, universe ) results = nodes.select { |star| Space::Universe.rand( universe[ :dice ][ :lonely_star ] ) > 0 } results.push nodes.first() if results.length == 0 return results end ## # Cosy stars have at least one planet # def self.populate_cosy_stars( nodes, cosy_stars, universe, universe_size, universe_contents ) cosy_stars.each do | star | planet = create_planet( nodes, universe, universe_size, universe_contents ) path = create_path( planet, star, universe, universe_size ) end universe_contents[ :planets ].times do star = cosy_stars[ Space::Universe.rand cosy_stars.length ] planet = create_planet( nodes, universe, universe_size, universe_contents ) path = create_path( planet, star, universe, universe_size ) end end ## # We created clusters of planets surrounding stars, so lets select those # def self.get_extended_clusters( clusters ) return clusters.map { | star | [ star ].concat star.connections } end ## # Append an asteroid to each cluster # def self.give_clusters_an_asteroid( nodes, clusters, universe, universe_size, universe_contents ) results = [] clusters.each do | c | # Create the asteroid and the path cluster_object = c[ Space::Universe.rand c.length ] asteroid = create_asteroid( nodes, universe, universe_size, universe_contents ) path = create_path( asteroid, cluster_object, universe, universe_size ) results.push( { :asteroid => asteroid, :cluster => c } ) end return results end ## # A part of the asteroids is sparse! # def self.assign_sparse_asteroids( universe, universe_contents ) universe_contents[ :sparse_asteroids ] = universe_contents[ :asteroids ] / universe[ :dice ][ :sparse_asteroid ].to_f sparse_variance = universe_contents[ :sparse_asteroids ] / 100 * universe[ :variance ] universe_contents[ :sparse_asteroids ] = ( universe_contents[ :sparse_asteroids ] + Space::Universe.rand( sparse_variance ) - sparse_variance / 2.to_f ).round universe_contents[ :asteroids ] -= universe_contents[ :sparse_asteroids ] return universe_contents[ :sparse_asteroids ] end ## # Connect asteroids to unconnected clusters # def self.interconnect_clusters_with_asteroids( nodes, asteroids, clusters, universe, universe_size, universe_contents ) total = universe_contents[ :asteroids ] while universe_contents[ :asteroids ] > 0 asteroids.each do | meta_a | asteroid = meta_a[ :asteroid ] cluster = meta_a[ :cluster ] # Create the asteroid and the path new_asteroid = create_asteroid( nodes, universe, universe_size, universe_contents ) path = create_path( new_asteroid, asteroid, universe, universe_size ) # Add the old asteroid to the cluster cluster.push asteroid meta_a[ :asteroid ] = new_asteroid # Connect to a cluster if universe_contents[ :asteroids ] > 0 if Space::Universe.rand( 100 ) < ( clusters.length / universe_contents[ :asteroids ] * 100 ) connect_clusters( new_asteroid, cluster, clusters, universe, universe_size, universe_contents ) end else break end percentage_log( ( total - universe_contents[ :asteroids ] ) / total.to_f * 100, "Interconnect clusters with asteroids" ) end end end ## # Connect two clusters using a asteroid # def self.connect_clusters( asteroid, asteroid_cluster, clusters, universe, universe_size, universe_contents ) cluster = clusters[ Space::Universe.rand clusters.length ] connectee = cluster[ Space::Universe.rand cluster.length ] path = create_path( connectee, asteroid, universe, universe_size ) clusters.delete cluster clusters.delete asteroid_cluster clusters.push( ( cluster + asteroid_cluster ).push asteroid ) end ## # Lets make sure all the clusters are connected! # def self.ensure_connected_clusters( clusters, universe, universe_size ) total = clusters.length while clusters.length > 1 # Find the clusters that are being connected left_cluster = clusters[ Space::Universe.rand clusters.length ] options = clusters.select { | c | c != left_cluster } right_cluster = options[ Space::Universe.rand options.length ] # Find the nodes to connect left_nodes = left_cluster.select { | n | !n.is_a? Space::Star } right_nodes = right_cluster.select { | n | !n.is_a? Space::Star } left_node = left_nodes[ Space::Universe.rand left_nodes.length ] right_node = right_nodes[ Space::Universe.rand right_nodes.length ] path = create_path( left_node, right_node, universe, universe_size ) clusters.delete left_cluster clusters.delete right_cluster clusters.push( left_cluster + right_cluster ) percentage_log( ( total - clusters.length ) / total.to_f * 100, "Ensure connected clusters" ) end end ## # Now process the sparse_asteroids # def self.connect_sparse_asteroids( nodes, clusters, universe, universe_size, universe_contents ) universe_contents[ :asteroids ] += universe_contents[ :sparse_asteroids ] total = universe_contents[ :asteroids ] while universe_contents[ :asteroids ] > 0 cluster = clusters.first cluster_object = cluster[ Space::Universe.rand cluster.length ] asteroid = create_asteroid( nodes, universe, universe_size, universe_contents ) path = create_path( asteroid, cluster_object, universe, universe_size ) cluster.push asteroid percentage_log( ( total - universe_contents[ :asteroids ] ) / total.to_f * 100, "Connecting sparse asteroids" ) end end ## # Do we still need to make some paths? # def self.overconnect_close_nodes( clusters, universe, universe_size ) total = universe_size[ :p ] overless_connected = clusters.first.select { | n | n.is_a? Space::Asteroid } while universe_size[ :p ] > 0 and overless_connected.length > 0 options = [] visited = [] # Get the left object left_object = overless_connected[ Space::Universe.rand overless_connected.length ] # Start travelling! travelling = universe[ :distances ][ :connecting ] recursive_traverse( travelling, left_object, options, visited ) options = options.select { |n| n != left_object and !n.connections.include?( left_object ) } if options.length === 0 overless_connected.delete left_object next end # Right object right_object = options[ Space::Universe.rand options.length ] path = create_path( left_object, right_object, universe, universe_size ) percentage_log( ( total - universe_size[ :p ] ) / total.to_f * 100, "Overconnecting close nodes" ) end end ## # Log percentage # def self.percentage_log( percentage, message ) print "\r \r" print "\r#{message}: #{percentage.round}%" end ## # Creates space from a set of options # def self.build( options ) Space::Universe.log "Creation of the Universe has started with #{ options }" ## # # results = Space::Universe.new( options ) universe = results.configuration universe_size = size( universe ) universe_contents = contents( universe, universe_size ) Space::Universe.log "Developing #{ universe_contents[ :stars ] } stars, mending #{ universe_contents[ :planets ] } planets, throwing #{ universe_contents[ :asteroids ] } asteroids, " + "totalling in #{ universe_size[ :n ] } nodes with #{ universe_size[ :f ] } faces and #{ universe_size[ :p ] } paths" nodes = [] groups = {} # Intial clustering groups[ :clusters ] = create_clusters( nodes, universe, universe_size, universe_contents ) groups[ :cosy_stars ] = get_cosy_stars( nodes, universe ) populate_cosy_stars( nodes, groups[ :cosy_stars ], universe, universe_size, universe_contents ) # Add a connection point groups[ :extended_clusters ] = get_extended_clusters( groups[ :clusters ] ) groups[ :asteroids ] = give_clusters_an_asteroid( nodes, groups[ :extended_clusters ], universe, universe_size, universe_contents ) assign_sparse_asteroids( universe, universe_contents ) # Connect those asteroids interconnect_clusters_with_asteroids( nodes, groups[ :asteroids ], groups[ :extended_clusters ], universe, universe_size, universe_contents ) ensure_connected_clusters( groups[ :extended_clusters ], universe, universe_size ) connect_sparse_asteroids( nodes, groups[ :extended_clusters ], universe, universe_size, universe_contents ) overconnect_close_nodes( groups[ :extended_clusters ], universe, universe_size ) print "\r \r" Space::Universe.log "The Universe has been created" results.fill nodes return results end ## # Recursively traverse a node # def self.recursive_traverse( travelling, node, endpoints, visited ) if travelling < 0 return end visited.push node endpoints.push node if node.is_a? Space::Asteroid node.paths.each { |p| if visited.include? p[ :to ] next end recursive_traverse( travelling - p[ :distance ], p[ :to ], endpoints, visited ) } end end end end
true
876a09cd7b69f47c484ef433d9f88f1a281a8237
Ruby
brendanr425/Intro-to-Ruby
/Intro-to-Ruby/exercises/exercise_13.rb
UTF-8
547
3.28125
3
[]
no_license
def assignment(arr) info = Hash.new info[:email] = arr[0] info[:address] = arr[1] info[:number] = arr[2] return info end contact_data = [["joe@email.com", "123 Main st.", "555-123-4567"], ["sally@email.com", "404 Not Found Dr.", "123-234-3454"]] contacts = {"Joe Smith" => {}, "Sally Johnson" => {}} info = contact_data.map{|arr| assignment(arr)} count = 0 contacts.each_key do |key| contacts[key] = info[count] count += 1 end puts "Joe's email: #{contacts["Joe Smith"][:email]}" puts "Sally's phone number: #{contacts["Joe Smith"][:number]}"
true
b16dec29b4d7ce358f2d9e3f7303513485aa4be8
Ruby
khashiyousefi/FoodNatic
/test/models/comment_test.rb
UTF-8
1,864
2.59375
3
[]
no_license
require 'test_helper' class CommentTest < ActiveSupport::TestCase test "comment should not save if empty comment" do c1 = Comment.new assert_not c1.save end test "Comment save in Recipe and User success" do c1 = Comment.new c1.comment_text = "test" # make a new user instance for c to save to u = User.new p = Preference.new s = Savedrecipe.new u.preference = p u.savedrecipe = s u.username="test" u.password="test" u.email="test@gmail.com" assert u.save # make a new recipe instance for c to save to r = Recipe.new assert r.save u.comments.push(c1) r.comments.push(c1) c1.user = u c1.recipe = r assert c1.save assert Comment.all.length == 3 # Check default vote value == 0 if user does not vote assert c1.vote == 0 c2 = Comment.new c2.comment_text = "test2" c2.vote = 1 u.comments.push(c2) r.comments.push(c2) c2.user = u c2.recipe = r assert c2.save assert Comment.all.length == 4 # Check if user votes, value is saved assert c2.vote == 1 end test "comment has a user_id but no recipe_id fail to save" do c = Comment.new c.comment_text = "test" # make a new user instance for c to save to u = User.new p = Preference.new s = Savedrecipe.new u.preference = p u.savedrecipe = s u.username="test" u.password="test" u.email="test@gmail.com" assert u.save # make a new recipe instance for c to save to u.comments.push(c) c.user = u assert_not c.save end test "comment has a recipe_id but no user_id fail to save" do c = Comment.new c.comment_text = "test" # make a new recipe instance for c to save to r = Recipe.new assert r.save r.comments.push(c) c.recipe = r assert_not c.save end end
true
bc4d2b131d5aa853824b3c354a90967aa152173b
Ruby
douglasdrumond/codility-lessons
/lesson2/FrogRiverOne.rb
UTF-8
382
3.28125
3
[]
no_license
# you can use puts for debugging purposes, e.g. # puts "this is a debug message" def solution(x, a) # write your code in Ruby 2.2 count = [0]*(x+1) sum = 0 a.each_with_index do |v, i| if count[v] == 0 count[v] = 1 sum += 1 if sum == x return i end end end return -1 end
true
040d04dfd1b2d72cd6cec12b3f4c550607882fd7
Ruby
gretchenista/skillcrush-ruby-challenge
/blog.rb
UTF-8
1,350
3.640625
4
[]
no_license
class Blog attr_accessor :title, :all_blog_posts, :total_blog_posts def initialize @created_at = Time.now puts "Name your blog" @title = gets.chomp @all_blog_posts = [] @total_blog_posts = 0 end def create_blogpost new_blog_post = Blogpost.new puts "This is my new blog post" @all_blog_posts << new_blog_post @total_blog_posts += 1 end def collect_blogposts return @all_blog_posts end def publish(all_blog_posts) all_blog_posts.each do |blogpost| puts blogpost.title puts blogpost.created_at puts blogpost.author puts blogpost.content end end end class Blogpost attr_accessor :title, :created_at, :author, :content def initialize @created_at = Time.now puts "What is your blog post" @title = gets.chomp puts "Who is writing" @author = gets.chomp puts "What are you writing" @content = gets.chomp end def edit_blog_content puts "New title" @title = gets.chomp puts "New text" @content = gets.chomp end end my_blog = Blog.new first_blog_post = my_blog.create_blogpost all_blog_posts = my_blog.collect_blogposts puts my_blog.inspect my_blog.publish(all_blog_posts)
true
95247614a5adfa4b752efed5b3423ffac3fb98fd
Ruby
is8r/top10games
/public/ruby/step2.rb
UTF-8
3,327
2.75
3
[]
no_license
require 'json' # -------------------------------------------------- # setting is_debug = false if is_debug file_input = 'dist/results_mini.json' file_output = 'dist/rank_mini.json' else file_input = 'dist/results.json' file_output = 'dist/rank.json' end # -------------------------------------------------- # function def format_width (s) s.tr!("0-9", "0-9") s.tr!("A-Z", "A-Z") s.tr!("a-z", "a-z") s.gsub!(" ", " ") s.gsub!("(", "(") s.gsub!(")", ")") end def format_number (s) s.gsub!(/XⅣ$/, "14" ) s.gsub!(/XIII$/, "13" ) s.gsub!(/XII$/, "12" ) s.gsub!(/XI$/, "11" ) s.gsub!(/Ⅸ$/, "9" ) s.gsub!(/X$/, "10" ) s.gsub!(/Ⅷ$/, "8" ) s.gsub!(/Ⅶ$/, "7" ) s.gsub!(/VII$/, "7" ) s.gsub!(/Ⅵ$/, "6" ) s.gsub!(/Ⅴ$/, "5" ) s.gsub!(/Ⅳ$/, "4" ) s.gsub!(/Ⅲ$/, "3" ) s.gsub!(/III$/, "3" ) s.gsub!(/Ⅱ$/, "2" ) s.gsub!(/Ⅰ$/, "1" ) s.gsub!(/II$/, "2" ) s.gsub!(/3rd$/, "3" ) s.gsub!(/2nd$/, "2" ) s.gsub!(/2ndG$/, "2G" ) s.gsub!(/\s\d/, '\2' ) end # -------------------------------------------------- # excute file = File.read(file_input) source = JSON.parse(file) texts = '' source.each do |i| unless i['text'].include?("RT @") texts += i['text'] end end texts.gsub!("#", "#") texts.gsub!("#自分の人生においてトップ10に入るゲームをあげてけ", "") ar = texts.split("\n") re = [] ar.each do |i| # フォーマットを統一したい format_width(i) format_number(i) i.gsub!(/^・/, "") i.gsub!(/^ /, "") i.gsub!("(SFC)", "") i.gsub!("(FC)", "") i.gsub!("(GB)", "") i.gsub!("(GC)", "") # 例外処理 i.gsub!(/^FFTA/, "ファイナルファンタジータクティクスアドバンス") i.gsub!(/^FFT/, "ファイナルファンタジータクティクス") i.gsub!(/^FF/i, "ファイナルファンタジー") i.gsub!(/^ドラクエ/, "ドラゴンクエスト") i.gsub!(/^DQ/i, "ドラゴンクエスト") i.gsub!("スト2", "ストリートファイター2" ) i.gsub!(/^スパロボ/, "スーパーロボット大戦") i.gsub!(/^モンハン/, "モンスターハンター") i.gsub!(/^MOTHER/i, "マザー") i.gsub!(/^skyrim/i, "スカイリム") i.gsub!(/^beatmania/i, "ビートマニア") i.gsub!(/^Minecraft/i, "マインクラフト") i.gsub!(/^GTAV/i, "GTA5") i.gsub!(/^MGS/i, "メタルギアソリッド") i.gsub!(/^MHP/i, "モンスターハンターポータブル") i.gsub!(/^PSO/i, "ファンタシースターオンライン") i.gsub!(/^COD/i, "Call of Duty") i.gsub!("Duty:", "Duty ") i.gsub!(/^KOF/i, "ザ・キング・オブ・ファイターズ") i.gsub!(/^TO/i, "テイルズオブ") i.gsub!(/^KH/i, "キングダムハーツ") i.gsub!(/^ /, "") i.gsub!(/^\s/, "") i.gsub!(/^ /, "") if i.include?("@") next elsif i.include?("やってみた") next elsif i.include?("越えられない壁") next elsif i.include?("順不同") next elsif i.empty? next else re.push i end end # create hash hash = {} re.each do |i| if hash.has_key?(i) hash[i] += 1 else hash[i] = 1 end end # 5票以下を削除 hash.delete_if {|key, val| val < 5 } # sort result = hash.sort_by{|key,val| -val} # array2hash h = Hash[*result.flatten] File.write(file_output, h.to_json)
true
edeacd6cf4cc313e02f6ca653bcaefb601837a6d
Ruby
ZASMan/learn_ruby
/04_pig_latin/pig_latin.rb
UTF-8
2,967
3.90625
4
[]
no_license
#write your code here #Update: Must be able to take in more than one word def translate(word) #In case there are multiple words, split into array seperated by spaces word_arr = word.split(" ") #Values for Vowels and Consonants vowels = ["a", "e", "i", "o", "u", "y"] consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "x", "z"] #Execute Same code if Length is Equal to 1 (one word input) if word_arr.length == 1 if vowels.include?(word[0]) word = word + "ay" elsif consonants.include?(word[0]) and consonants.include?(word[1]) and consonants.include?(word[2]) first_letter = word[0] second_letter = word[1] third_letter = word[2] no_first_three_letters_word = word [1, word.length] word = no_first_three_letters_word + first_letter + second_letter + third_letter + "ay" #First Two Letters are Consonants elsif consonants.include?(word[0]) and consonants.include?(word[1]) first_letter = word[0] second_letter = word[1] no_first_two_letters_word = word [2, word.length] word = no_first_two_letters_word + first_letter + second_letter + "ay" #First Letter is Consonant elsif consonants.include?(word[0]) first_letter = word[0] no_first_letter_word = word[1, word.length] word = no_first_letter_word + first_letter + "ay" #Valid String is Not Passed Through else word = "Word must contain begin with a valid letter" end #There are Multiple Words in the Array elsif word_arr.length > 1 #New Array to Push Individual Pig Latin Words To new_word_arr = [] #Now We Need a Loop to Run All the Code Similar to lines 12-34 word_arr.each do |word| if vowels.include?(word[0]) word = word + "ay" elsif consonants.include?(word[0]) and consonants.include?(word[1]) and consonants.include?(word[2]) first_letter = word[0] second_letter = word[1] third_letter = word[2] no_first_three_letters_word = word [1, word.length] word = no_first_three_letters_word + first_letter + second_letter + third_letter + "ay" #Push to New Word Array Below new_word_arr.push(word) #First Two Letters are Consonants elsif consonants.include?(word[0]) and consonants.include?(word[1]) first_letter = word[0] second_letter = word[1] no_first_two_letters_word = word [2, word.length] word = no_first_two_letters_word + first_letter + second_letter + "ay" #Push to New Word Array Below new_word_arr.push(word) #First Letter is Consonant elsif consonants.include?(word[0]) first_letter = word[0] no_first_letter_word = word[1, word.length] word = no_first_letter_word + first_letter + "ay" #Push to New Word Array Below new_word_arr.push(word) #Valid String is Not Passed Through else word = "Word must contain begin with a valid letter" end #End of Each Loop below end #Make new_word_arr into a single string with spaces word = new_word_arr.join(" ") end end
true
22f92c3ff7ce840425e80255788c02bc380640e9
Ruby
davidbrahiam/credit_card
/credit_card_test.rb
UTF-8
3,636
2.984375
3
[]
no_license
require "test/unit" require_relative './credit_card' class CreditCardTest < Test::Unit::TestCase include ModuleCreditCardHelper # Check types of credit cards def test_types cards_list = [ {type: "VISA", status: :success, number: '4111111111111111'}, {type: "VISA", status: :success, number: '4111111111111'}, {type: "VISA", status: :success, number: '4012888888881881'}, {type: "AMEX", status: :success, number: '378282246310005'}, {type: "Discover", status: :success, number: '6011111111111117'}, {type: "Unknown", status: :error, number: '9111111111111111'}, {type: "MasterCard", status: :success, number: '5105105105105106'}, {type: "Unknown", status: :error, number: '5105 1051 0510 5106'}, ] cards_list.each do |card| assert_equal(Hash, ModuleCreditCardHelper.check_type(card[:number]).class) assert_equal(card[:status], ModuleCreditCardHelper.check_type(card[:number])[:status]) assert_equal(card[:type], ModuleCreditCardHelper.check_type(card[:number])[:type]) end end # Check the sum of numbers cards def test_numbers assert_equal("valid", ModuleCreditCardHelper.check_sum('4111111111111111')) assert_equal("invalid", ModuleCreditCardHelper.check_sum('9111111111111111')) assert_equal("valid", ModuleCreditCardHelper.check_sum('911111111111111')) assert_equal("valid", ModuleCreditCardHelper.check_sum('378282246310005')) assert_equal("valid", ModuleCreditCardHelper.check_sum('5105105105105100')) assert_equal("invalid", ModuleCreditCardHelper.check_sum('5105 1051 0510 5106')) assert_equal("invalid", ModuleCreditCardHelper.check_sum('5105 1051 0510 5100')) assert_equal("invalid", ModuleCreditCardHelper.check_sum('5105105105105106')) end # Check validation from some cards def test_cards assert_equal('VISA: 4111111111111111 (valid)', CreditCard.new().validate('4111111111111111') ) assert_equal('VISA: 4111111111111 (invalid)', CreditCard.new().validate('4111111111111') ) assert_equal('VISA: 4012888888881881 (valid)', CreditCard.new().validate('4012888888881881') ) assert_equal('AMEX: 378282246310005 (valid)', CreditCard.new().validate('378282246310005') ) assert_equal('Discover: 6011111111111117 (valid)', CreditCard.new().validate('6011111111111117') ) assert_equal('MasterCard: 5105105105105100 (valid)', CreditCard.new().validate('5105105105105100') ) assert_equal('MasterCard: 5105105105105106 (invalid)', CreditCard.new().validate('5105 1051 0510 5106') ) assert_equal('Unknown: 9111111111111111 (invalid)', CreditCard.new().validate('9111111111111111') ) assert_equal('MasterCard: 5155327746759207 (valid)', CreditCard.new().validate('5155327746759207') ) assert_equal('Discover: 6011951670514932 (valid)', CreditCard.new().validate('6011951670514932') ) assert_equal('Unknown: 515527746759207 (invalid)', CreditCard.new().validate('515527746759207') ) assert_equal('Error of Character', CreditCard.new().validate('911111eqweweeqw1111111111') ) assert_equal('Error of Character', CreditCard.new().validate('') ) assert_equal('Error of Character', CreditCard.new().validate('312;3"11232-30eqwe09qw8093812') ) assert_equal('AMEX: 378282246310005 (valid)', CreditCard.new().validate('3782 82246310005') ) assert_equal('Error of Character', CreditCard.new().validate('ddjoidj1o2ij312j312oi3') ) end end
true
540d5d64f6b9c9db92d2544ce8de0d1c1fffbcb2
Ruby
yumojin/Example-Sketches
/samples/processing_app/library/video/movie/loop.rb
UTF-8
428
2.609375
3
[ "MIT" ]
permissive
# Loop. # # Shows how to load and play a QuickTime movie file. # # load_libraries :video, :video_event include_package 'processing.video' attr_reader :movie def setup size(640, 360) background(0) # Load and play the video in a loop @movie = Movie.new(self, 'transit.mov') movie.loop end def draw image(movie, 0, 0, width, height) end # use camel case to match java reflect method def movieEvent(m) m.read end
true
76bad2cf7235626bd6a62b0db953880f4a659f82
Ruby
pivotib/radiant-content-pieces-extension
/spec/models/content_piece_spec.rb
UTF-8
1,640
2.765625
3
[]
no_license
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe ContentPiece do before do @content_piece = ContentPiece.instance @content_piece.clear end it "should be a singleton" do lambda { ContentPiece.instance }.should_not raise_error end describe "<< method" do it "should be able to add a piece" do lambda { @content_piece << valid_hash }.should change(@content_piece, :size).by(1) end it "should allow a hash with a name" do lambda { @content_piece << valid_hash(:name => "foo") }.should change(@content_piece, :size).by(1) end it "should not allow a hash without a name" do lambda { @content_piece << valid_hash(:name => nil) }.should_not change(@content_piece, :size) end it "should allow a hash with a path_method" do lambda { @content_piece << valid_hash(:path_method => "foo") }.should change(@content_piece, :size).by(1) end it "should not allow a hash without a path_method" do lambda { @content_piece << valid_hash(:path_method => nil) }.should_not change(@content_piece, :size) end end describe "while enumerating" do before do @content_piece << valid_hash(:name => "foo") << valid_hash(:name => "baz") end it "should be able to enumerate over the object" do lambda{ @content_piece.each{|piece| } }.should_not raise_error end it "should be able to map :name" do @content_piece.map{|p| p[:name] }.should == ["foo", "baz"] end end protected def valid_hash(options={}) { :name => "foo", :path_method => 'bar' }.merge(options) end end
true
6e0aab08c4d7611d2127d0c38a507e51c4091741
Ruby
andygnewman/unbeatable-noughts-and-crosses
/app/tictactoe.rb
UTF-8
932
2.71875
3
[]
no_license
require 'sinatra' require_relative './lib/game' class TicTacToe < Sinatra::Base set :root, File.dirname(__FILE__) get '/' do erb :index end get '/ready/?:starts' do GAME = Game.new redirect to('/play') if params[:starts] == 'computer' redirect to('/human') end get '/play' do GAME.computer_turn redirect to('/winner') unless GAME.winner == false @empty_cells = GAME.empty_cells_array @board = GAME.current_board erb :play end get '/human' do @empty_cells = GAME.empty_cells_array @board = GAME.current_board erb :play end get '/human_choice/?:cell' do GAME.human_turn(params[:cell]) redirect to('/play') unless GAME.winner != false redirect to('/winner') end get '/winner' do @winner = GAME.winner @board = GAME.current_board erb :winner end # start the server if ruby file executed directly run! if app_file == $0 end
true
e0e47f093d427fcc7c743d6071cf33fe561bbf2c
Ruby
su-kun1899/rubybook
/chapter11/regex.rb
UTF-8
202
3.03125
3
[]
no_license
p "カフェラテ".match?(/ラテ/) p "ティーラテ".match?(/ラテ/) p "モカ".match?(/ラテ/) %w(カフェラテ モカ コーヒー).each do |drink| puts drink if drink.match?(/ラテ/) end
true
0b4e1fa5b3d41a5561a1c40a8fa920980afb21d1
Ruby
kevin4052/codewars
/ruby/6kyu/multiples-of-3-or-5.rb
UTF-8
402
3.578125
4
[]
no_license
# https://www.codewars.com/kata/514b92a657cdc65150000006/ruby # --------------my solution-------------- def solution(number) sum = 0; for i in 0..(number-1) if i % 5 == 0 || i % 3 == 0 then sum += i; end end return sum; end # --------------best practice-------------- def solution(number) (1...number).select {|i| i%3==0 || i%5==0}.inject(:+) end
true
fd5d7ebe94917c288f1c5852e6790116bcd8a989
Ruby
codingsnippets/quest-till-done
/app/models/record.rb
UTF-8
945
2.53125
3
[]
no_license
# Record base model for Link, Note and Image class Record < ActiveRecord::Base searchkick extend FriendlyId friendly_id :description, use: [:slugged, :history] attr_accessor :encounter, :quest, :questname # Record belongs to a quest belongs_to :quest # Record belongs to a encounter belongs_to :encounter # Record belongs to a user belongs_to :user validates_associated :encounter # Define scope for Single Table Inheritance scope :link, ->{where(type: "Link")} scope :note, ->{where(type: "Note")} def assign_encounter self.encounter_id = Encounter.where(:user_id => self.user.id).last.id self.save end def to_s "#{self.description} ( for the Quest #{self.quest.to_s} )" end @child_classes = [] def self.inherited(child) @child_classes << child super # important! end def self.child_classes @child_classes end def to_link self.quest.to_link end end
true
b7cea27d5055b63d487a9d17b20f6d6b81dd57cd
Ruby
rondale-sc/method_source-expressions
/lib/method_source-expressions/expression_collection.rb
UTF-8
786
2.8125
3
[ "MIT" ]
permissive
module MethodSource::Expressions class ExpressionCollection attr_reader :expressions def initialize(expressions) @top_node, *@expressions = expressions end def direct_descendents(collection=expressions) child_expressions.map{ |child| expression_or_collection(child) } end def source @top_node.source end private attr_reader :top_node def child_expressions expressions.reject do |outer| expressions.any? {|inner| outer.within(inner) } end end def expression_or_collection(expression) sub_children = expressions.select{|e| e.within(expression) } if sub_children.length > 0 self.class.new([expression, *sub_children]) else expression end end end end
true
d55ea22b13af81918dc35f40fbb7318b7992dece
Ruby
Kweiss/Ruby-Code
/test_statistics/lib/calculate_mean.rb
UTF-8
632
4.03125
4
[]
no_license
# Calculate the mean of a series of numbers class CalculateMean def initialize(ary, population="population") @series_of_nums = ary @pop = "population" end def mean sum = 0 # Add together the sum of all numbers in the set @series_of_nums.each { |x| sum += x } # If @series_of_nums is the full population: # mean = sum / @series_of_nums.size if @pop == "population" ( sum / @series_of_nums.size ).to_f # Otherwise, if @series_of_nums is a sample size of a much larger population: # mean = sum / @series_of_nums.size - 1 elsif @pop == "sample" ( sum / @series_of_nums.size - 1 ).to_f end end end
true
622421ba3e7aa9568e9bafd87ed01217dc1df832
Ruby
jeff-chen/Bowling-cucumber-demo
/app/models/game.rb
UTF-8
459
3.15625
3
[]
no_license
class Game < ActiveRecord::Base has_many :sessions def next_turn sessions.map{|i| i.next_turn}.min end def last_session sessions.sort{|a, b| a.next_turn <=> b.next_turn}.first end def has_winner? winner = true sessions.each do |session| winner &= (session.next_turn == 11) end winner end def winner return nil unless has_winner? sessions.max_by{|session| session.total_score}.player end end
true
0ded5704e6b1db4af83003a7c9820d81c0121f02
Ruby
learn-co-students/West-se-111620
/06-ruby-small-group-review/ix/lib/Manager.rb
UTF-8
736
3.3125
3
[]
no_license
class Manager attr_accessor :name, :department, :age @@all = [] def initialize(name, department, age) @name = name @department = department @age = age @@all << self end def self.all @@all end def self.all_departments @@all.map{|manager| manager.department}.uniq end def hire_employee(employee, start_date) Contract.new(employee, self, start_date) end def contracts Contract.all.select{|contract| contract.manager == self} end def employees self.contracts.map{|contract| contract.employee} end def self.average_age @@all.sum{|manager| manager.age} / @@all.length.to_f end end
true
0b53141bc316cd1474cee7797663b0dc2feb7342
Ruby
staceyko/playlister-rb-web-0715-public
/lib/artist.rb
UTF-8
2,292
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist @@all_artists = [] attr_accessor :name, :songs, :genres def initialize @songs = [] @genres = [] @@all_artists << self end def self.reset_artists @@all_artists.clear end def self.all @@all_artists end def self.count @@all_artists.count end require 'pry' def add_song(song) @songs << song @genres << song.genre song.genre.artists << self if song.genre # if song.genre # song.genre.artists << self # binding.pry end end # # Song # # belongs_to :artist # # belongs_to :genre # # Artist # # has_many :songs # # has_many :genres, through: songs # # Genre # # has_many :songs # # has_many artists, through: songs # class Artist # attr_accessor :name, :songs, :genres # @@all = [] # #if you have a class and trying to keep track of all the instances of the class, we are going to create self.all and have some sort of an array that keeps track of every instance. # def initialize # @@all << self # @songs = [] # @genres = [] # end # def add_song(song) # @songs << song # song.artist = self # if song.genre #put if statement, because we don't want to do this if its nil, if there is no genre. # song.genre.artists << self # self.genres << song.genre #self is song.artist # end # song # end # def add_songs(song_array) # songs_array.each {|song| add_song(song)} # end # def self.all # @@all # end # def self_reset_all # self.all.clear # end # def self.count # self.all.count # end # def self.find_by_name(artist_name) # self.all.find{|artist| artist.name == artist_name} # end # def self.create_by_name(artist_name) # artist = Artist.new #can also do artist = self.new # artist.name = artist_name # artist # end # end # # class Artist # # attr_accessor :name, :artists, :genres # # @@artists = [] # # def self.reset_artists # # @@artists.clear # # end # # def self.count # # @@artists.length # # end # # def self.all # # @@artists # # end # # def initialize # # @name = name # # @songs = [] # # @@artists << self # # @genres = [] # # end # # def add_song(song) # # @songs << song # # @genres << song.genre # # end # # end
true
e262959f494e132320f43067bc875e7d4d0a2050
Ruby
SashaTlr/restaurant_grades
/model.rb
UTF-8
683
3.109375
3
[]
no_license
class RestaurantModel attr_reader :restaurant_name, :cuisine, :address, :zip, :phone def initialize(args = {}) @restaurant_name = args["dba"] @cuisine = args["cuisine_description"] @building = args["building"].nil? ? "" : args["building"].strip @street = args["street"].nil? ? "" : args["street"].strip @address = "#{@building} #{@street}" @zip = args["zipcode"] @phone = args["phone"] end def to_s "#{cuisine}: #{self.restaurant_name} #{address}" end end class Directory attr_reader :restaurants def initialize(restaurants) @restaurants = restaurants end def to_s @restaurants.each { |restaurant| restaurant.to_s} end end
true
d6a240e3720d7983b4000b3eab01360d6c43b87f
Ruby
chanwoohill/math_game.rb
/question.rb
UTF-8
324
3.546875
4
[]
no_license
class Question attr_reader :solution def initialize @num1 = rand(21) @num2 = rand(21) @operator = [:+, :-, :*].sample @solution = @num1.send(@operator, @num2) end def get_question "What is #{@num1} #{@operator} #{@num2} ?" end def correct?(answer) answer.to_i == @solution end end
true
61d9896a43ac6a9ec78b76761d1d50fc4eb39ce3
Ruby
jackCHH/riftodds
/lib/riotapi.rb
UTF-8
628
2.6875
3
[]
no_license
require 'httparty' require 'uri' class RiotApi BASE_URL = "https://na.api.pvp.net" API_KEY = "?api_key=4ac9d17c-8e89-44d9-99cd-cb806bd078b9" def get_summoner_id(name) summoner_url = "#{BASE_URL}/api/lol/na/v1.4/summoner/by-name/#{name}#{API_KEY}" parse_json(summoner_url) end def get_full_stats(id) stat_url = "#{BASE_URL}/api/lol/na/v1.3/stats/by-summoner/#{id}/ranked#{API_KEY}" parse_json(stat_url) end def get_champion champion_url = "#{BASE_URL}/api/lol/static-data/na/v1.2/champion#{API_KEY}" parse_json(champion_url) end def parse_json(url) response = HTTParty.get(url) json = JSON.parse(response.body) json end end
true
fc253d56beceeca5b8a570e4d8a212d978f11338
Ruby
walidwahed/ls
/exercises/120-oop_problems/easy1/02.rb
UTF-8
1,096
4.5625
5
[]
no_license
# What's the Output? # Take a look at the following code: class Pet attr_reader :name def initialize(name) @name = name.to_s # calling to_s on a String does not create a new object end def to_s @name.upcase! "My name is #{@name}." end end name = 'Fluffy' fluffy = Pet.new(name) puts fluffy.name # => 'Fluffy' puts fluffy # => "My name is FLUFFY." (upcase! is a destructive method) puts fluffy.name # => 'FLUFFY' puts name # => 'FLUFFY' # What output does this code print? Fix this class so that there are no surprises waiting in store for the unsuspecting developer. # to fix this cose, would change `upcase!` to `upcase` # problem is that in this case, Ruby appears to pass by reference, allowing the instance methods to mutate the caller, which is the same object local variable outside of the class `name` is pointing at # further exploration name = 42 fluffy = Pet.new(name) name += 1 # this is reassignment. Name is now pointing at a new object, Fixnum 43. puts fluffy.name # => '42' puts fluffy # => 'My name is 42' puts fluffy.name # => '42' puts name # 43
true
de66747aca6db7bee8495113da38c236c02da7cb
Ruby
StuartChartersE22/w3d5_CodeClan_Cinema_homework
/console.rb
UTF-8
2,206
2.8125
3
[]
no_license
require("pry") require_relative("./models/film.rb") require_relative("./models/customer.rb") require_relative("./models/ticket.rb") require_relative("./models/screening.rb") Ticket.delete_all() Screening.delete_all() Customer.delete_all() Film.delete_all() customer1 = Customer.new({ "name" => "Stuart", "wallet" => 5000 }) customer2 = Customer.new({ "name" => "Joe", "wallet" => 1000 }) customer3 = Customer.new({ "name" => "Ro", "wallet" => 10000 }) customer1.save() customer2.save() customer3.save() film1 = Film.new({ "name" => "Crank", "price" => 500 }) film2 = Film.new({ "name" => "Dumbo", "price" => 750 }) film3 = Film.new({ "name" => "Anastasia", "price" => 1500 }) film1.save() film2.save() film3.save() screening1 = Screening.new({ "film_id" => film1.id(), "show_time" => "12:45", "capacity" => "3" }) screening2 = Screening.new({ "film_id" => film2.id(), "show_time" => "00:15", "capacity" => "10" }) screening3 = Screening.new({ "film_id" => film3.id(), "show_time" => "13:00", "capacity" => "10" }) screening4 = Screening.new({ "film_id" => film1.id(), "show_time" => "06:00", "capacity" => "10" }) screening5 = Screening.new({ "film_id" => film2.id(), "show_time" => "11:00", "capacity" => "10" }) screening6 = Screening.new({ "film_id" => film3.id(), "show_time" => "10:00", "capacity" => "10" }) screening1.save() screening2.save() screening3.save() screening4.save() screening5.save() screening6.save() ticket1 = Ticket.new({ "customer_id" => customer1.id(), "screening_id" => screening3.id() }) ticket2 = Ticket.new({ "customer_id" => customer2.id(), "screening_id" => screening1.id() }) ticket3 = Ticket.new({ "customer_id" => customer1.id(), "screening_id" => screening2.id() }) ticket4 = Ticket.new({ "customer_id" => customer1.id(), "screening_id" => screening4.id() }) ticket5 = Ticket.new({ "customer_id" => customer3.id(), "screening_id" => screening1.id() }) ticket6 = Ticket.new({ "customer_id" => customer1.id(), "screening_id" => screening1.id() }) ticket1.save() ticket2.save() ticket3.save() ticket4.save() ticket5.save() ticket6.save() binding.pry nil
true
9b361fa092d3dc1f99e54e296e88bdf9a90f6545
Ruby
RedRobster66/lab-ruby-apartments
/apartments.rb
UTF-8
3,357
3.25
3
[]
no_license
class CreditScoreError < Exception end class BadTenantCreditError < Exception end class NotEnoughRoomError < Exception end class NoSuchTenantError < Exception end class NoSuchApartmentError < Exception end class ApartmentIsOccupiedError < Exception end def calculate_credit_rating credit_score case credit_score when 0..559 :Bad when 560..659 :Mediocre when 660..724 :Good when 725..759 :Great else :Excellent end end class Building attr_reader :address def initialize address @address = address @apartments = [] @total_sqr_ft = (apartment.sqr_ft).reduce(:+) @total_revenue = (apartment.rent).reduce(:+) @all_tenants = (apartment.tenant) def add_apartment apartment @apartments << apartment end def apartments @apartments.dup end def credit_separate apartments end def remove_apartment apartment_number, force_removal=false index = @apartments.index { |a| a.number == apartment_number} raise NoSuchApartmentError.new apartment_number if index.nil? apartment = @apartments[index] raise ApartmentIsOccupiedError.new if !force_removal && apartment.has_tenants? @apartment.delete_at(index) end end class Tenant attr_reader :name, :age, :credit_score def initialize name, age, credit_score @name = name @age = age if credit_score < 0 raise CreditScoreError.new 'Score cannot be negative' elsif credit_score > 800 raise CreditScoreError.new 'Score cannot be greater than 800' else @credit_score = credit_score end end def credit_rating end end begin rob = Tenant.new('Rob', 45, -20) rescue Exception => e p e end class Apartment attr_reader :number, :rent, :sqr_ft def initialize number, rent, sqr_ft, num_of_bedrooms, num_of_bath @number = number @rent = rent @sqr_ft = sqr_ft @num_of_bedrooms = num_of_bedrooms @num_of_bath = num_of_bath @tenants = [] end def add_tenant tenant raise BadTenantCreditError.new tenant if tenant.credit_rating == :Bad raise NotEnoughRoomError.new tenant if tenants.length == num_of_bedrooms @tenants << tenant end #tenant can be an object or a name def remove_tenant tenant if tenant.to_s == tenant index = @tenants.index { |t| t.name == tenant} if index.nil? not_found = true else @tenants.delete_at index end else deleted = @tenants.delete tenant not_found = deleted.nil? end raise NoSuchTenantError.new tenant if not_found end def remove_tenants @tenants.clear # can also replace with an empty array [] end def average_credit # @tenants.inject(0){|sum,t| sum + t.credit_score}.to_f / tenants.length # @tenants.map{|t| t.credit_score}.reduce(:+).to_f / @tenants.length @tenants.map(&:credit_score).reduce(:+).to_f / tenants.length end def credit_rating calculate_credit_rating(average_credit_score) end def is_vacant? @tenants.present? end end
true
1e8efefcc93c4202e382530090acf9cd37acb851
Ruby
georgejeffery/badges-and-schedules-london-web-121018
/conference_badges.rb
UTF-8
469
3.828125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) "Hello, my name is #{name}."# end def batch_badge_creator(names) badges=[] names.each do |i| badges.push(badge_maker(i)) end badges end def assign_rooms(names) rooms=[] names.each_with_index do |i, index| rooms.push("Hello, #{i}! You'll be assigned to room #{index+1}!") end rooms end def printer(names) batch_badge_creator(names).each do |i| puts i end assign_rooms(names).each do |i| puts i end end
true
56b7517498c322bcc2f9f22cefb57f0547421a56
Ruby
quintel/etlocal
/app/services/dataset_combiner.rb
UTF-8
6,657
3.125
3
[ "MIT" ]
permissive
# frozen_string_literal: true # The DatasetCombiner parent class acts as the interface through which smaller areas can be # combined into a bigger one. It validates user input, sets defaults and then delegates the work # to the ValueProcessor and DataExporter that do the actual combining. # See the 'initialize' method for (expected) arguments. # # Example usage: # # # Init the combiner with information on source- and target datasets # combiner = DatasetCombiner.new( # target_dataset_geo_id: 'PV20', # source_data_year: '2019', # source_dataset_geo_ids: %w[GM306 GM307 GM308], # target_area_name: 'Groningen', # Optional # target_country_name: 'nl2019', # Optional # migration_slug: 'update_2019' # Optional # ) # # # Instruct the combiner to combine the datasets into a new one # # (lets ValueProcessor do its job, see for details on combining) # combiner.combine_datasets # # # Instruct the combiner to export the new dataset to several files # # (lets DataExporter do its job, see for details on exporting) # migration_filename = combiner.export_data # class DatasetCombiner # Arguments: # target_dataset_geo_id: Identifier of dataset to combine into, e.g.: 'PV20' # source_data_year: The year over which new data should be calculated # source_dataset_geo_ids: Identifiers for areas to be combined, e.g.: ['GM306','GM307'] # target_area_name (optional): Name of combined area, e.g.: 'Groningen' # target_country_name (optional): Name of country of the target dataset, e.g. 'nl2019' # migration_slug (optional): Short description of migration in lowercase and underscores, e.g.: 'update_2023' def initialize( target_dataset_geo_id:, source_data_year:, source_dataset_geo_ids:, target_area_name: nil, target_country_name: nil, migration_slug: nil ) @target_dataset_geo_id = target_dataset_geo_id @source_data_year = source_data_year @source_dataset_geo_ids = source_dataset_geo_ids @target_area_name = target_area_name @target_country_name = target_country_name @migration_slug = migration_slug # Validate whether all required arguments are present validate_input # Set defaults for any non-mandatory arguments that were omitted set_defaults @source_datasets = Dataset.where(geo_id: @source_dataset_geo_ids) # Validate whether all source datasets are up to date until at least the requested source_data_year validate_dataset_data_year end def combine_datasets @combined_item_values = DatasetCombiner::ValueProcessor.perform(@source_datasets) end def export_data DatasetCombiner::DataExporter.new( target_dataset_geo_id: @target_dataset_geo_id, target_area_name: @target_area_name, target_country_name: @target_country_name, migration_slug: @migration_slug, combined_item_values: @combined_item_values, source_area_names: @source_datasets.pluck(:name) ).perform end private def validate_input # Check for missing mandatory arguments empty_args = { target_dataset_geo_id: @target_dataset_geo_id, source_data_year: @source_data_year, source_dataset_geo_ids: @source_dataset_geo_ids }.select { |_arg, v| v.blank? } if empty_args.present? argument_error("The following mandatory arguments were omitted: #{empty_args.keys.join(', ')}") end # Check target_dataset_geo_id unless @target_dataset_geo_id.present? && @target_dataset_geo_id.is_a?(String) argument_error('The target_dataset_geo_id should be a (numeric) string') end @target_dataset = Dataset.find_by(geo_id: @target_dataset_geo_id) # No target_area_name was provided, so we should derive it from an existing dataset # with the given 'target_dataset_geo_id'. We raise an error if we can't. if @target_area_name.blank? && (@target_dataset.nil? || @target_dataset.name.blank?) argument_error('No target_area_name was provided, and it cannot be derived through the target_dataset_geo_id') end # If the target dataset is a province or RES region we need to include a country name. # This should either be passed as the 'target_country_name' argument, or be derived # from the dataset that belongs to the given 'target_dataset_geo_id'. # We raise an error if this is not the case. if @target_dataset_geo_id.start_with?('PV', 'RES') && @target_country_name.blank? && @target_dataset.nil? argument_error( <<~MSG You are attempting to create a combined dataset for a province or RES-region which required a country name. The country name could not be derived from an existing dataset with geo-id '#{@target_dataset_geo_id}' however. Please pass the country name as the "target_country_name" argument.\n MSG ) end # Check if the source_data_year lies between 1900 and the current year. unless @source_data_year.to_i.between?(1900, Time.zone.today.year) argument_error("The source_data_year provided is not a valid year. A valid year is between 1900 and #{Time.zone.today.year}") end # Check source_dataset_geo_ids unless @source_dataset_geo_ids.is_a?(Array) && @source_dataset_geo_ids.all? { |id| id.is_a?(String) } argument_error('The source_dataset_geo_ids should be a set of ids') end end def validate_dataset_data_year if @source_datasets.empty? argument_error('Could not find any datasets for the given source_dataset_geo_ids') end outdated_datasets = @source_datasets.select do |set| set.editable_attributes.find('analysis_year').value.to_i < @source_data_year.to_i end if outdated_datasets.present? argument_error( "The following datasets are not up to date to the requested source_data_year (#{@source_data_year}):\n #{outdated_datasets.pluck(:name).join(', ')}\n" ) end end def set_defaults # No target_area_name was provided. Derive it from the target dataset. if @target_area_name.blank? @target_area_name = @target_dataset.name end # No target_country_name was provided, but it is required. Derive it from the target dataset. if @target_country_name.blank? && @target_dataset_geo_id.start_with?('PV', 'RES') @target_country_name = @target_dataset.country end # No migration slug was provided. Derive it from the given source_data_year if @migration_slug.blank? @migration_slug = @source_data_year.to_s end end def argument_error(msg) raise ArgumentError, "#{msg}. Aborting." end end
true
3b2997b23a6c8bbb4b54290c06af12d54a317135
Ruby
erictaelee/tech_interview_practice
/most_frequent_letter.rb
UTF-8
683
4.3125
4
[]
no_license
# Given a string, find the most commonly occurring letter. # Input: “peter piper picked a peck of pickled peppers” # Output: “p” def frequent_letter(string) letter_counts = {} index = 0 most_frequent_letter = "" most_frequent_count = 0 while index < string.length if letter_counts[string[index]] letter_counts[string[index]] += 1 else letter_counts[string[index]] = 1 end if letter_counts[string[index]] > most_frequent_count most_frequent_count = letter_counts[string[index]] most_frequent_letter = string[index] end index += 1 end return most_frequent_letter end p frequent_letter("peter piper picked a peck of pickled peppers")
true
4586f8403e31ba470f4ebb647925657e8da87230
Ruby
hhf666feng/gitlab
/lib/container_registry/repository.rb
UTF-8
886
2.53125
3
[ "MIT" ]
permissive
module ContainerRegistry class Repository attr_reader :registry, :name delegate :client, to: :registry def initialize(registry, name) @registry, @name = registry, name end def path [registry.path, name].compact.join('/') end def tag(tag) ContainerRegistry::Tag.new(self, tag) end def manifest return @manifest if defined?(@manifest) @manifest = client.repository_tags(name) end def valid? manifest.present? end def tags return @tags if defined?(@tags) return [] unless manifest && manifest['tags'] @tags = manifest['tags'].map do |tag| ContainerRegistry::Tag.new(self, tag) end end def blob(config) ContainerRegistry::Blob.new(self, config) end def delete_tags return unless tags tags.all?(&:delete) end end end
true
669020987216085ab31d3844fa70be5cbb97e260
Ruby
cozziekuns/Sandra
/tile_util.rb
UTF-8
432
2.96875
3
[]
no_license
#============================================================================== # ** TileUtil #============================================================================== module TileUtil def self.tile_value(tile) return 10 if self.jihai?(tile) return tile % 9 + 1 end def self.tile_suit(tile) return -1 if self.jihai?(tile) return tile / 9 end def self.jihai?(tile) return tile >= 27 end end
true
bcaf2dfa0f1e336f99aa27b5cbc6722855552d75
Ruby
karthickpdy/CP
/Hackerrank/max_draws.rb
UTF-8
56
3.1875
3
[]
no_license
t = gets.to_i t.times do n = gets.to_i puts n + 1 end
true
a9f624848c9f8c8f1511f42935000b5e3a6126b6
Ruby
cha63506/library-227
/work/deprecated/requirements.rb
UTF-8
2,152
2.6875
3
[ "BSD-2-Clause" ]
permissive
class Library # class Requirements include Enumerable # def initialize(location) @location = location @dependencies = nil end # Location of project. def location @location end # Returns an array of `[name, constraint]`. def dependencies @dependencies || load_require_file end # TODO: split runtime from all others def runtime dependencies end # def exist? File.exist?(File.join(location, 'REQUIRE')) end # def load_require_file return [] #require 'yaml' dependencies = [] file = File.join(location, 'REQUIRE') if File.exist?(file) begin data = YAML.load(File.new(file)) list = [] data.each do |type, reqs| list.concat(reqs) end list.each do |dep| name, *vers = dep.split(/\s+/) vers = vers.join('') vers = nil if vers.empty? dependencies << [name, vers] end rescue $stderr.puts "roll: failed to load requirements -- #{file}" dependencies = [] end end @dependencies = dependencies end # Returns a list of Library and/or [name, vers] entries. # A Libray entry means the library was loaded, whereas the # name/vers array means it failed. (TODO: Best way to do this?) # # TODO: don't do stdout here def verify(verbose=false) libs, fail = [], [] dependencies.each do |name, vers| lib = Library[name, vers] if lib libs << lib $stdout.puts " [LOAD] #{name} #{vers}" if verbose unless libs.include?(lib) or fail.include?(luib) lib.requirements.verify(verbose) end else fail << [name, vers] $stdout.puts " [FAIL] #{name} #{vers}" if verbose end end return libs, fail end # def each #:yield: dependencies.each{|x| yield(x) } end # def size dependencies.size end # def empty? dependencies.empty? end end end
true
46d75dc3471f32493fa432b4d92556c6b95b6120
Ruby
ashabbir/summarization
/main.rb
UTF-8
3,887
2.5625
3
[]
no_license
require 'sinatra' require 'yaml' require 'pry' require 'json' require 'sinatra/reloader' if development? require_relative 'lib/file_processor' require_relative 'lib/summarize' require_relative 'lib/mail_reader' require_relative 'lib/news_feed' require_relative 'lib/sentimental' set :static, true set :root, File.dirname(__FILE__) set :public, 'public' not_found do erb :not_found end # login get '/' do erb :login, :layout => false end # login get '/contact' do erb :contact end get '/cnn' do config = YAML.load_file File.expand_path('./config.yml', File.dirname(__FILE__)) drop = config[:drop_path] drop = File.expand_path(".././drop/" , __FILE__) + '/' fetcher = FileProcessor.new name: "test.txt" , drop: drop fetcher.fetch_if_needed @data = fetcher.open_file s = Summarize.new text: @data, percent: 7, cutoff_percent: 50 s.process s.calculate_cutoff @arr = s.highlight @data = @data.gsub("\r\n", "<p>") erb :summary end get '/alice' do config = YAML.load_file File.expand_path('./config.yml', File.dirname(__FILE__)) drop = config[:drop_path] drop = File.expand_path(".././drop/" , __FILE__) + '/' fetcher = FileProcessor.new name: "text.txt" , url: 'http://icourse.cuc.edu.cn/computernetworks/labs/alice.txt' , drop: drop fetcher.fetch_if_needed @data = fetcher.open_file s = Summarize.new text: @data, percent: 70, cutoff_percent: 50 s.process s.calculate_cutoff @arr = s.highlight @data = @data.gsub("\r\n", "<p>") erb :summary end get '/gmail' do erb :gmail end post '/gmail' do username = params[:user_name] password = params[:password] summarize = params[:summarize] highlight = params[:highlight] days = params[:days] m = MailReader.new username: username , password: password @msg = m.process days.to_i @arr = [] @msg.each do |m| s = Summarize.new text: m, percent: summarize.to_i, cutoff_percent: highlight.to_i s.process s.calculate_cutoff @arr.push s.highlight.join end @arr = @arr.reverse erb :result end get '/rss' do rss_reader = NewsFeed.new url: 'http://rss.cnn.com/rss/cnn_world.rss' @feed = rss_reader.get_feed @arr = [] @feed.each do |m| s = Summarize.new text: m, percent: 90, cutoff_percent: 10 s.process s.calculate_cutoff @arr.push s.highlight.join end rss_reader = NewsFeed.new url: 'http://rss.cnn.com/rss/cnn_topstories.rss' @feed = rss_reader.get_feed @feed.each do |m| s = Summarize.new text: m, percent: 90, cutoff_percent: 10 s.process s.calculate_cutoff @arr.push s.highlight.join end erb :result end post '/summarize' do content_type :json request.body.rewind json = request.body.read json = json.scrub.gsub(/\r/, " ").gsub(/\n/, " ").strip @request_payload = JSON.parse json, :quirks_mode => true word_count = @request_payload["word"].to_f text = @request_payload["text"] total = text.split.size.to_f pct = (word_count / total) * 100 @summary = [] s = Summarize.new text: text, percent: pct, cutoff_percent: 0 s.process @summary = s.plaintext.join sen = Sentimental.new text: @summary sen.process @result = Hash["total_sentiment" => sen.total, "calculated_sentiment" => sen.calculated , "summmary" => @summary , "verdict" => sen.verdict , "score_part" => sen.scores] @result.to_json end get '/sentiment' do content_type :json config = YAML.load_file File.expand_path('./config.yml', File.dirname(__FILE__)) drop = config[:drop_path] drop = File.expand_path(".././drop/" , __FILE__) + '/' fetcher = FileProcessor.new name: "test.txt" , drop: drop fetcher.fetch_if_needed text = fetcher.open_file s = Sentimental.new text: text s.process @result = Hash["total" => s.total, "scores" => s.scores , "sentences" => s.sentences , "calculated" => s.calculated] @result.to_json end
true
e74781c7d61f96ba49599baf46ff37cc903e9d28
Ruby
ConorFl/overflow
/app/controllers/votes_controller.rb
UTF-8
919
2.53125
3
[]
no_license
class VotesController < ApplicationController def upvotes changevotes(params[:class],1) end def downvotes changevotes(params[:class],-1) end private def changevotes(type,howmuch) @typeClass = Kernel.const_get(type) user =User.find(session[:current_user_id]) @type = @typeClass.find(params[:id]) @question = Question.find(params[:question_id]) if @type.votes.size == 0# if the question has no votes @vote = Vote.create(:number=>1) @vote.user = user @type.votes << @vote redirect_to question_path(@question) elsif @type.votes.first.number == 1 redirect_to question_path(@question) else @votes_number = @type.votes.first.number @type.votes.first.update_attributes(:number=>@votes_number+howmuch) @vote = @type.votes.first user.votes << @vote redirect_to question_path(@question) end end end
true
c66c861f6f5cfe508ab6b98bf7cade50f1761e55
Ruby
ncm/countwords
/optimized.rb
UTF-8
401
2.921875
3
[ "MIT" ]
permissive
counts = Hash.new(0) bufsize = 64*1024 remaining = '' while 1 do chunk = STDIN.read(bufsize) if !chunk break end chunk = remaining + chunk last_lf = chunk.rindex("\n") if !last_lf remaining = '' else remaining = chunk[last_lf+1..] chunk = chunk[..last_lf] end chunk.downcase.split.each{ |w| counts[w] += 1 } end counts.sort_by{|k,v| -v}.each{|k,v| puts "#{k} #{v}"}
true
9c8edf0c4ac401dfcb66d1733ad4b314e55b0ad4
Ruby
j-sm-n/black_thursday
/test/merchant_item_analyst_test.rb
UTF-8
2,539
2.671875
3
[]
no_license
require './test/test_helper' require './lib/merchant_item_analyst' require './lib/sales_analyst' require 'pry' class MerchantItemAnalystTest < Minitest::Test attr_reader :mi_anlyst def setup invoice_path = "./test/fixtures/31_invoices.csv" merchant_path = "./test/fixtures/3_merchants_v2.csv" invoice_item_path = "./test/fixtures/134_invoice_items.csv" transaction_path = "./data/transactions.csv" item_path = "./data/items.csv" file_paths = {:merchants => merchant_path, :items => item_path, :invoice_items => invoice_item_path, :invoices => invoice_path, :transactions => transaction_path} engine = SalesEngine.from_csv(file_paths) parent_analyst = SalesAnalyst.new(engine) @mi_anlyst = MerchantItemAnalyst.new(12337105, parent_analyst) end def test_it_can_find_a_merchants_paid_in_full_invoices invoices = mi_anlyst.merchant_paid_in_full_invoices assert_equal 7, invoices.length end def test_it_can_find_paid_in_full_invoice_items invoice_items = mi_anlyst.merchant_paid_in_full_invoice_items assert_equal 35, invoice_items.length end def test_it_can_group_invoice_items_by_quantity grouped_invoice_items = mi_anlyst.group_invoice_items_by_quantity assert_equal 10, grouped_invoice_items.length assert_equal (1..10).to_a, grouped_invoice_items.keys.sort end def test_it_can_group_invoice_items_by_revenue grouped_invoice_items = mi_anlyst.group_invoice_items_by_revenue actual = grouped_invoice_items.keys.include?(BigDecimal.new(179376)/100) assert_equal 34, grouped_invoice_items.length assert_equal true, actual end def test_it_can_find_the_max_quantity_invoice_items invoice_items = mi_anlyst.max_quantity_invoice_items assert_equal 4, invoice_items.length assert_equal 263431273, invoice_items.first.item_id end def test_it_can_find_the_max_revenue_invoice_items invoice_items = mi_anlyst.max_revenue_invoice_items assert_equal 1, invoice_items.length assert_equal 263463003, invoice_items.first.item_id end def test_it_can_find_most_sold_item_for_merchant items = mi_anlyst.most_sold_item_for_merchant assert_equal 4, items.length assert_instance_of Item, items.first assert_equal 263431273, items.first.id end def test_it_can_find_best_item_for_merchant items = mi_anlyst.best_item_for_merchant assert_instance_of Item, items assert_equal 263463003, items.id end end
true
1c4be1435bf89cfdd97a41f70d10765938b113c5
Ruby
rkjfb/mazes
/book_files/recursive_division.rb
UTF-8
1,773
3.484375
3
[]
no_license
#--- # Excerpted from "Mazes for Programmers", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information. #--- ROOMS = false class RecursiveDivision def self.on(grid) @grid = grid @grid.each_cell do |cell| cell.neighbors.each { |n| cell.link(n, false) } end divide(0, 0, @grid.rows, grid.columns) end def self.divide(row, column, height, width) if ROOMS return if height <= 1 || width <= 1 || height < 5 && width < 5 && rand(4) == 0 else return if height <= 1 || width <= 1 end if height > width divide_horizontally(row, column, height, width) else divide_vertically(row, column, height, width) end end def self.divide_horizontally(row, column, height, width) divide_south_of = rand(height-1) passage_at = rand(width) width.times do |x| next if passage_at == x cell = @grid[row+divide_south_of, column+x] cell.unlink(cell.south) end divide(row, column, divide_south_of+1, width) divide(row+divide_south_of+1, column, height-divide_south_of-1, width) end def self.divide_vertically(row, column, height, width) divide_east_of = rand(width-1) passage_at = rand(height) height.times do |y| next if passage_at == y cell = @grid[row+y, column+divide_east_of] cell.unlink(cell.east) end divide(row, column, height, divide_east_of+1) divide(row, column+divide_east_of+1, height, width-divide_east_of-1) end end
true
59fd523700297df4c67ae1c42bb89249a0bc0e85
Ruby
mkrobert/ruby_projectilemotion
/projectilemotion.rb
UTF-8
1,707
3.578125
4
[ "MIT" ]
permissive
#this library is located at #https://github.com/mkrobert/ruby_projectilemotion include Math #required kinematics library is located at #https://github.com/mkrobert/ruby_kinematics require './kinematics' class ProjectileMotion < Kinematics def findVIX(x,y,h,th) if (x[0] != nil) return x elsif (th != nil) && (h[0] != nil) return h[0] * cos(th * PI / 180.0) return sqrt((h[0] ** 2) - (y[0] ** 2)) end end def findVIY(x,y,h,th) if (y[0] != nil) return y elsif (th != nil) && (h[0] != nil) return h[0] * sin(th * PI / 180.0) else return sqrt((h[0] ** 2) - (x[0] ** 2)) end end def findVIH(x,y,h,th) if (h[0] != nil) return h elsif (th != nil) && (x[0] != nil) return x[0] * tan(th * PI / 180.0) else return sqrt((x[0] ** 2) + (y[0] ** 2)) end end def findTh(x,y,h,th) if (th != nil) return th else return atan(findVIY(x,y,h,th,t) / findVIX(x,y,h,th) * PI / 180.0) end end def findDeltaX(x,y,h,th) if (x[3] != nil) return x[3] else return x[0] * (findT(y[0],y[1],y[2],y[3],y[4])) end end def findDeltaY(x,y,h,th) if (y[3] != nil) return y[3] else return y[0] * (findT(y[0],y[1],y[2],y[3],y[4])) else end #implementation example #A water balloon is thrown horizontally with a speed of 8.31m/s from the roof of a building of height 23.0m. #How far does the balloon travel horizontally before striking the ground? promot = ProjectileMotion.new #puts promot.findDeltaX([8.31,nil,nil,nil,nil],[0,nil,-9.8,-23.0,nil],nil,nil).to_s puts promot.findDeltaX([8.31,nil,nil,nil,nil],[0,nil,-9.8,-23.0,nil],nil,nil).to_s
true
44c1cd1369d47f6378b12ef1b40b0fbf7e0073ca
Ruby
jaimerson/bakeru
/lib/bakeru/background.rb
UTF-8
3,169
2.984375
3
[]
no_license
require 'gosu' require 'bakeru/zorder' require 'gl' require 'glu' require 'glut' module Bakeru # This class loads and draws the tiles for a given location. class Background include Gl include Glu attr_reader :location, :game, :player # A central point to modifying tile size TILE_SIZE = 1 # @param [Bakeru::Game] game - a game instance def initialize(game, location, player) @game = game @location = location @player = player available_tiles = Dir.glob('assets/sprites/tiles/floor/*').map do |file| [file.split('/').last.split('.').first, Gosu::Image.new(file)] end.to_h @tiles = location.tiles.map do |line| line.map do |tile_name| available_tiles[tile_name] end end end def update end def draw glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # clear the screen and the depth buffer #glMatrixMode(matrix) indicates that following [matrix] is going to get used glMatrixMode(GL_PROJECTION) # The projection matrix is responsible for adding perspective to our scene. glLoadIdentity # Resets current modelview matrix # Calculates aspect ratio of the window. Gets perspective view. 45 is degree viewing angle, (0.1, 100) are ranges how deep can we draw into the screen gluPerspective(90.0, game.width / game.height, 0.1, 100.0) glMatrixMode(GL_MODELVIEW) # The modelview matrix is where object information is stored. glLoadIdentity glTranslate(-10, -10.0, -8) # Moving function from the current point by x,y,z change glShadeModel(GL_SMOOTH) glMaterialfv(GL_FRONT, GL_SPECULAR, [0.3, 0.3, 0.3, 0.0]) glMaterialfv(GL_FRONT, GL_SHININESS, [100.0, 0.5, 0.0, 0.0]) glLightfv(GL_LIGHT0, GL_POSITION, [(player.x / game.width.to_f) * 8.0 + TILE_SIZE, (game.height - player.y) / 100.0, player.magic / 5.0, 0.45]) glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); # Think 3-d coordinate system (x,y,z). +- on each movies on that axis #glTranslate(-1, -1, -1) # Moving function from the current point by x,y,z change glEnable(GL_TEXTURE_2D) # enables two-dimensional texturing to perform @tiles.each_with_index do |tiles, line| tiles.each_with_index do |tile, column| #tile.draw line * TILE_SIZE, column * TILE_SIZE, ZOrder::BACKGROUND tex_info = tile.gl_tex_info glBindTexture(GL_TEXTURE_2D, tex_info.tex_name) # bing named texture to a target glBegin(GL_QUADS) # begin drawing model glTexCoord2d(tex_info.left, tex_info.top) #sets texture coordinates glVertex3d(column, line, 0) # place a point at (x,y,z) location from the current point glTexCoord2d(tex_info.right, tex_info.top) glVertex3d(column + TILE_SIZE, line, 0) glTexCoord2d(tex_info.right, tex_info.bottom) glVertex3d(column + TILE_SIZE, line + TILE_SIZE, 0) glTexCoord2d(tex_info.left, tex_info.bottom) glVertex3d(column, line + TILE_SIZE, 0) glEnd end end end end end
true
f73d9e72baecf64a4787e243d45b3c5f816db13b
Ruby
biradarganesh25/hw-acceptance-unit-test-cycle
/rottenpotatoes/app/helpers/movies_helper.rb
UTF-8
237
2.90625
3
[]
no_license
module MoviesHelper # Checks if a number is odd: def oddness(count) count.odd? ? "odd" : "even" end def get_movie_director(movie) if movie.director == nil return "N/A" end return movie.director end end
true
ae39f8da25880fda90114a9bdaa059739473d881
Ruby
amcmullen9291/countdown-to-midnight-onl01-seng-ft-030220
/countdown.rb
UTF-8
307
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def countdown(seconds) while seconds>0 do puts"#{seconds} SECOND(S)!" seconds-= 1 end "HAPPY NEW YEAR!" end def countdown_with_sleep(seconds) while seconds>0 do puts"#{seconds} SECOND(S)!" sleep 1 seconds-= 1 end "HAPPY NEW YEAR!" end
true
6090a1d01c845c96b90788d5f73424febfd5b6e7
Ruby
chrisdziewa/event_manager
/lib/event_manager.rb
UTF-8
3,688
3.109375
3
[]
no_license
require "csv" require 'sunlight/congress' require 'erb' require 'date' Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5" def clean_zipcode(zipcode) zipcode.to_s.rjust(5, "0")[0..4] end def legislators_by_zipcode(zipcode) legislators = Sunlight::Congress::Legislator.by_zipcode(zipcode) end def save_thank_you_letters(id, form_letter) Dir.mkdir("output") unless Dir.exists? "output" filename = "output/thanks_#{id}.html" File.open(filename, "w") do |file| file.puts form_letter end end def save_mobile_contacts(mobile_template) Dir.mkdir("reports") unless Dir.exists? "reports" filename = "reports/mobile_alerts.html" File.open(filename, "w") do |file| file.puts mobile_template end end def save_hours_report(reg_hours_template) Dir.mkdir("reports") unless Dir.exists? "reports" filename = "reports/registration-hours.html" File.open(filename, "w") do |file| file.puts reg_hours_template end end def clean_phone_number(phone_number) phone_number = phone_number.split(/[^0-9]/).join("") length = phone_number.length if length< 10 || phone_number.nil? || length > 11 return "bad number" elsif length == 11 && phone_number[0] != "1" return "bad number" elsif length == 11 && phone_number[0] == "1" return phone_number[1..11] else return phone_number end end def format_date_time(date_time) register_hour = DateTime.strptime(date_time, '%m/%d/%y %H:%M') end def get_most_popular_key(hours_hash) hours_hash.max_by{|k,v| v}[0] end def get_day_name(date) Date::DAYNAMES[date.wday] end puts "Event Manager Initialized!" # Thank you template template_letter = File.read "form_letter.erb" erb_template = ERB.new template_letter # mobile alerts file mobile_alerts = File.read "mobile_alerts.erb" mobile_template = ERB.new mobile_alerts mobile_list = [] # track hours of registration for report hours_tracker = {} (0..24).each { | hour | hours_tracker[hour] = 0 } #track days that participants registered on reg_days_tracker = {} Date::DAYNAMES.each do |day| reg_days_tracker[day] = 0 end #registration hour report template reg_hours = File.read "reg_hour_reports.erb" reg_hours_template = ERB.new reg_hours ## Iterate through attendees contents = CSV.open("event_attendees.csv", headers: true, header_converters: :symbol) contents.each do | row | id = row[0] name = row[:first_name] last_name = row[:last_name] phone = row[:homephone] # Get dates and times and convert to DateTime formatted_date_time = format_date_time(row[:regdate]) register_hour = formatted_date_time.hour # add a tally to current our in hours_tracker hours_tracker[register_hour] += 1 # find legislators in the area of valid zipcodes zipcode = clean_zipcode(row[:zipcode]) legislators = legislators_by_zipcode(zipcode) # Build thank you letters form_letter = erb_template.result(binding) save_thank_you_letters(id, form_letter) # track registration day frequencies day = get_day_name(formatted_date_time) reg_days_tracker[day] += 1 if clean_phone_number(phone) != "bad number" mobile_list.push([last_name, name , clean_phone_number(phone)]) end end popular_day = get_most_popular_key(reg_days_tracker) # Hours with most signups popular_hour = get_most_popular_key(hours_tracker) # Create hour report webpage completed_hours_report = reg_hours_template.result(binding) save_hours_report(completed_hours_report) # Create a webpage for valid mobile contacts completed_mobile_list = mobile_template.result(binding) save_mobile_contacts(completed_mobile_list)
true
72d7190263f7cf3f2f5b33b45733d0ef6f1d8f71
Ruby
yanjustino/dojos_ruby
/pedra_papel_tesoura/partida.rb
UTF-8
557
3.015625
3
[ "MIT" ]
permissive
class Partida def initialize @vitorias = [['tesoura', 'papel'], ['papel', 'pedra'], ['pedra', 'tesoura']] end def jogar (jogador1, jogador2) @partida = [jogador1, jogador2] definir_vencedor || 'empate' end private def definir_vencedor jogadas.each { |jogada| return jogada.first if vencedor? jogada } unless empate? end def empate? @partida.first == @partida.last end def jogadas @partida.permutation end def vencedor? (jogada) @vitorias.include? jogada end end
true
caf075077fad74ee24f82573cfcbd6afd084671b
Ruby
petrul/misc
/stories/analyze/calculate-users-score.rb
UTF-8
3,496
3
3
[]
no_license
#! /usr/bin/ruby # script to get users that were closest or furthest from the final answers # (in order to see if somebody answered randomly) def run_sql_query(sql_query) require "mysql" dbh = Mysql.real_connect("infres5.enst.fr", "dimulesc", "cselumid", "dimulesc") #dbh = Mysql.real_connect("localhost", "dadi", "dadi", "story_comparison_dev") res = dbh.query(sql_query) result = [] while row = res.fetch_hash do result << row end return result rescue Mysql::Error => e puts "Error code: #{e.errno}" puts "Error message: #{e.error}" puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate") ensure # disconnect from server dbh.close if dbh end def get_all_story_ids run_sql_query("select distinct storyid from InsertionResult order by storyid") #.collect {|i| i['storyid'] } end def get_all_users run_sql_query("select * from User") #.collect {|i| i['login'] } end # parse the text file that contains summed comparisons so that we don't # have to compute again from the database # returns a hash<storyid, hash<array, array>> (for each story, for each version comparison as 2-element array, the versions as 2-element array) def parse_r_datafile filename = "stories-r-datafile.data" stories_summed_results = {} counter = 0 File.open(filename) do |f| f.each_line do |line| if (line =~ /story_(\d+) (\d)-(\d) (\d+) (\d+)/) then raise "expected something like 'story_9 1-2 23 13'" unless $1 && $2 && $3 && $4 && $5 crt_story_hash = stories_summed_results[$1] || {} key = [$2, $3] value = [$4, $5] crt_story_hash[key] = value stories_summed_results[$1] = crt_story_hash # puts " #$1 , #$2, #$3, #$4 #$5" counter += 1 end end end puts "parsed #{counter} lines from file #{filename}" stories_summed_results end def main(args) average_comparisons = parse_r_datafile() storyids = get_all_story_ids() raise "expected 20 stories" if storyids.length != 20 users = get_all_users() users_who_didnot_complete = [] user_who_completed = [] users.each { |u| escaped_u = u['login'].sub("\'", "\'\'") # for d'alessandro comparisons = run_sql_query("select * from InsertionResult where user = '#{escaped_u}'") if (comparisons.length != 20) users_who_didnot_complete << u puts "WARNING : user #{u['login']} only did #{comparisons.length} comparisons" else user_who_completed << u score = 0 comparisons.each { |comp| crtstoryid = comp['storyid'] chosenOption = comp['chosenOption'] _tmp = [comp['optionPresented1'],comp['optionPresented2']].sort() opt1 = _tmp[0]; opt2 = _tmp[1]; avg_opt1 = average_comparisons[crtstoryid][[opt1,opt2]][0] avg_opt2 = average_comparisons[crtstoryid][[opt1,opt2]][1] good_option = opt1 if (avg_opt2 > avg_opt2) good_option = opt2 end if chosenOption == good_option score += 1 # puts "good" else puts "user #{u['login']} : incorrect choice for story #{crtstoryid}, #{opt1} vs #{opt2} = #{avg_opt1}/#{avg_opt2}, user chose #{chosenOption}" end } u['score'] = score end } puts "nr of users who completed the test is #{user_who_completed.size()}" user_who_completed.sort {|a, b| b['score'] <=> a['score'] }.each { |user| puts "#{user['login']}(#{user['email']}) => #{user['score']}" } end main(ARGV)
true
3cbf407585c3961a44c5127e4984fc0c6d2fd047
Ruby
jtrtj/laugh_tracks
/spec/models/comedian_spec.rb
UTF-8
1,080
2.78125
3
[]
no_license
RSpec.describe Comedian do describe 'Validations' do describe 'Required Field(s)' do it 'should be invalid if missing a name' do comic = Comedian.create(age: 48) expect(comic).to_not be_valid end it 'should be invalid if missing an age' do comic = Comedian.create(name: 'Mitch Hedberg') expect(comic).to_not be_valid end end end describe 'class methods' do it '#avg_age' do Comedian.create(name: 'Jerry', age: 62) Comedian.create(name: 'Larry', age: 69) expect(Comedian.avg_age).to eq(65.5) end end describe 'instance methods' do it '#specials_count' do jerry = Comedian.create(name: 'Jerry', age: 62) larry = Comedian.create(name: 'Larry', age: 69) special_1 = jerry.specials.create(name: 'Jerry Seinfeld HBO Special') special_2 = jerry.specials.create(name: 'Comedy Central Special') special_3 = larry.specials.create(name: 'Really Funny Special') expect(jerry.specials_count).to eq(2) expect(larry.specials_count).to eq(1) end end end
true
d4d5a8ddb27cb7f4613cf95fcb219d40abd77788
Ruby
tanaken0515/ruby-examination
/silver/studies/syntax/case04_refactoring.rb
UTF-8
160
3.53125
4
[]
no_license
def hoge(*args, &block) block.call(*args) end hoge(1,2,3,4) do |*args| p args # => [1, 2, 3, 4] p args.length > 0 ? "hello" : args # => "hello" end
true