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
b49a112e264e3a81a321d65ca4054c59efd61afe
Ruby
BenUlcoq/PP0109
/calculator_test.rb
UTF-8
549
3.28125
3
[]
no_license
require 'test/unit' require_relative 'calculator' class CalculatorTest < Test::Unit::TestCase def test_add total = add(1,2) assert_equal(3, total) end def test_subtract total = subtract(10,5) assert_equal(5, total) end def test_multiply total = multiply(5,4) assert_equal(20, total) end def test_divide total = divide(14,7) assert_equal(2.to_f, total) end def test_square total = square(5) assert_equal(25, total) end end
true
d675ca984e6dc0e40eaccd0933ea90d9191eb6ac
Ruby
pelicularities/katas
/phone_book.rb
UTF-8
936
4.125
4
[]
no_license
# Enter your code here. Read input from STDIN. Print output to STDOUT # Input format: # (Int) n = number of entries in phone book # (str) name phone_number # ... repeated n times # (str) name # ... repeated until end of input # get number of entries in phone book n = gets.chomp.to_i # populate phone book phone_book = {} n.times do input = gets.chomp puts "you entered #{input}" entry = input.split(' ') p entry # entry[0] is name, entry[1] is phone number phone_book[entry[0]] = entry[1] p phone_book end # get names to look up until end of input loop do name = gets # stop execution if there is no input break if name.nil? # remove newline at end of name name.chomp! # for debugging sanity break if name.empty? # look up the name in the phone book if phone_book[name].nil? puts "Not found" else puts "#{name}=#{phone_book[name]}" end end
true
52e23cc11d8d53f3ba4ee9934c3557c42a0cd58f
Ruby
freebz/Mastering-Ruby-Closures
/ch02/ex2-7.rb
UTF-8
361
2.828125
3
[]
no_license
# Block Pattern #2: Managing Resources f = File.open('Leo Tolstoy - War and Peace.txt', 'w') f << "Well, Prince, so Genoa and Lucca" f << " are now just family estates of the Buonapartes." f.close File.open('Leo Tolstoy - War and Peace.txt', 'w') do |f| f << "Well, Prince, so Genoa and Lucca" f << " are now just family estates of the Buonapartes." end
true
58892b8d4c5c119501c7bea7399a52d4340f40cd
Ruby
hoongman/borisbikes
/lib/borisbikes.rb
UTF-8
344
2.53125
3
[]
no_license
require_relative 'bike' require_relative 'person' require_relative 'station' require_relative 'van' require_relative 'garage' bike1=Bike.new(false) bike2=Bike.new(false) bike3=Bike.new(false) bike4=Bike.new(true) station1 = Station.new([bike1,bike2,bike3,bike4]) station2 = Station.new person = Person.new garage = Garage.new van = Van.new
true
b843fa1a52a0bc35cb410309b6df112446837bd9
Ruby
sdmalek44/black_thursday
/lib/item_repository.rb
UTF-8
1,256
2.90625
3
[]
no_license
require_relative 'repository' require_relative 'item' require 'time' class ItemRepository include Repository def initialize(loaded_file) @repository = loaded_file.map { |item| Item.new(item) } end def find_by_name(name) all.find { |item| item.name == name } end def find_all_with_description(description) all.find_all { |item| item.description.casecmp(description).zero? } end def find_all_by_price(price) all.find_all { |item| item.unit_price.to_f == price.to_f } end def find_all_by_price_in_range(range) all.find_all { |item| range.include?(item.unit_price.to_f) } end def find_all_by_merchant_id(merchant_id) all.find_all { |item| item.merchant_id == merchant_id } end def create(attributes) attributes[:id] = new_highest_id @repository.push(Item.new(attributes)) end def update(id, attributes) item = find_by_id(id) return item if item.nil? item.update_name(attributes[:name]) unless attributes[:name].nil? item.update_description(attributes[:description]) unless attributes[:description].nil? item.update_unit_price(attributes[:unit_price]) unless attributes[:unit_price].nil? item.new_update_time(Time.now.utc) if attributes.length.positive? end end
true
a25e2d1d92843b6a871bab76a07227dff96253b3
Ruby
shioimm/til
/practices/druby/druby_book/dcp.rb
UTF-8
1,039
2.828125
3
[]
no_license
# 参照: dRubyによる分散・Webプログラミング require 'drb/drb' class DCP include DRbUndumped def size(fname) File.lstat(fname).size end def fetch(fname) File.open(fname, 'rb') do |fp| while buf = fp.read(4096) yield buf end end end def store_from(there, fname) size = there.size(fname) wrote = 0 File.open(fname, 'wb') do |fp| there.fetch(fname) do |buf| wrote += fp.write(buf) yield([wrote, size]) if block_given? nil end end wrote end def copy(uri, fname) there = DRbObject.new_with_uri(uri) store_from(there, fname) do |wrote, size| puts "#{wrote * 100 / size}" end end end if __FILE__ == $0 if ARGV[0] == '-server' ARGV.shift DRb.start_service(ARGV.shift, DCP.new) puts DRb.uri DRb.thread.join else uri = ARGV.shift fname = ARGV.shift raise('usage: dcp.rb URI filename') if uri.nil? || fname.nil? DRb.start_service DCP.new.copy(uri, fname) end end
true
289668dd482a202b4213227eaa8a07ea6ab6d48e
Ruby
blakemiles/ruby
/studio_game/studio_game_mod10.rb
UTF-8
988
3.875
4
[]
no_license
class Player def score @health + @name.length end def initialize(name, health=100) @name = name.capitalize @health = health end def to_s "I'm #{@name} with a health of #{@health} and a score of #{score}." end def blam @health -= 10 puts "#{@name} got blammed!" end def w00t @health += 15 puts "#{@name} got w00ted!" end end class Game def initialize(title) @title = title @players = [] end attr_reader :title def add_player(a_player) @players.push(a_player) end def play puts "There are #{@players.size} players in #{@title}: " @players.each do |player| puts player end @players.each do |player| player.blam player.w00t player.w00t puts player end end end player1 = Player.new("moe") player2 = Player.new("curly", 125) player3 = Player.new("Lawrence", 60) knuckleheads = Game.new("Knuckleheads") knuckleheads.add_player(player1) knuckleheads.add_player(player2) knuckleheads.add_player(player3) knuckleheads.play
true
f237cab7a58193f33433fc6a129e8007f7da5fd0
Ruby
braiba/telemetrics-project-ruby
/test/models/journey_test.rb
UTF-8
693
2.515625
3
[]
no_license
require 'test_helper' class JourneyTest < ActiveSupport::TestCase def setup @journey = Journey.find(1) end test 'highest point' do lat_long = @journey.highest_point assert_in_delta lat_long.latitude, 51.5056, 0.0001 assert_in_delta lat_long.longitude, 0.0756, 0.0001 end test 'lowest altitude' do assert_in_delta 5.00, @journey.min_altitude, 0.0001 end test 'central point stays the same' do first = @journey.central_point second = @journey.central_point assert_same first, second end test 'highest point stays the same' do first = @journey.highest_point second = @journey.highest_point assert_same first, second end end
true
7d767c16b4c50363bc581f19dc6945e5597e2c96
Ruby
seaneshbaugh/portfolio
/test/validators/javascript_validator_test.rb
UTF-8
1,150
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'test_helper' class JavascriptValidatorTest < ActiveSupport::TestCase class DummyClass include ActiveModel::Model include ActiveModel::Validations attr_accessor :script validates :script, javascript: true end test 'valid JavaScript' do dummy_object = DummyClass.new dummy_object.script = 'console.log("test");' assert dummy_object.valid? end test 'invalid JavaScript on first line' do dummy_object = DummyClass.new dummy_object.script = 'function(x, y, { return x + y; }' assert_not dummy_object.valid? assert_equal(["SyntaxError: Function statements require a function name at line 1\n function(x, y, { return x + y; }\n^^^^^^^^"], dummy_object.errors[:script]) end test 'invalid JavaScript on second line' do dummy_object = DummyClass.new dummy_object.script = "console.log(\"test\");\nfunction(x, y, { return x + y; }" assert_not dummy_object.valid? assert_equal(["SyntaxError: Function statements require a function name at line 2\n function(x, y, { return x + y; }\n^^^^^^^^"], dummy_object.errors[:script]) end end
true
8f8f8921b82f6cdf81a3cae42781a9bcdc74b157
Ruby
cranieri/checkout-system
/lib/item.rb
UTF-8
178
2.8125
3
[]
no_license
class Item attr_reader :name attr_accessor :price def initialize(code) @name = Products::PRODUCTS[code][:name] @price = Products::PRODUCTS[code][:price] end end
true
d9462ab7485a833058f61d1d12c9d42747aa1629
Ruby
ngeballe/ls-exercises-challenges
/medium2/other files/other practice/own_each_with_object_and_reduce.rb
UTF-8
1,023
3.890625
4
[]
no_license
require 'pry' def each_with_object(array, object) array.each do |item| yield(item, object) end object end def reduce(array, accumulator = nil) accumulator ||= array.shift array.each do |item| accumulator = yield(accumulator, item) end accumulator end # In reduce, goal is one thing -- it returns accumulator # In EWO, goal is many things -- many to many # EWO won't work if the object you want to carry is immutable -- e.g. number, symbol # p each_with_object([*1..5], {}) { |n, result| result[n] = n**2 } == { 1 => 1, 2 => 4, 3 => 9, 4 => 16, 5 => 25 } # p each_with_object(%w(a b c d e), []) { |letter, result| result << letter.upcase * 2 } == %w(AA BB CC DD EE) # # p reduce([*1..100]) { |sum, n| sum + n } == 5050 # # p reduce([*'a'..'h'], '...') { |word, letter| letter + word } == 'hgfedcba...' # p reduce([*1..5]) { |product, num| num * product } == 120 b = [:tom, :dick, :harry] b.each_with_object(:'') do |sym, new_sym| binding.pry new_sym = (new_sym.to_s + sym.to_s).to_sym end
true
c8f10587effa56f1f549de1fd1da15d204da41d2
Ruby
rpardee/pci4r
/lib/filtering.rb
UTF-8
19,047
3.140625
3
[]
no_license
require "set" require "stemmer" ## # This module provides a number of +Classifier+ classes that are instantiated, # trained with sample text, and used to classify new bits of text. The base # class, +Classifier+, provides the basic capabilities. Two sub-classes, # +NaiveBayes+ and +Fisher+ provide more specific classification abilities. # # All of these classes require the same basic steps to be useful: # * Create a new instance, passing a block to extract features from the text # * Train the classifier by invoking the +train+ method as needed # * Have the classifier classify new, unseen text (varies by sub-class) module Filtering module Persistence ## # This class is the adapter between our generic persistence interface # and the core <tt>ActiveRecord</tt> library class ActiveRecordAdapter ## # Initialize <tt>ActiveRecord</tt> persistence with the same configuration # options passed to <tt>ActiveRecord::Base.establish_connection</tt> # === Example # Filtering::Persistence::ActiveRecordAdapter.new(:adapter => "sqlite", :database => "dbfile") # # Filtering::Persistence::ActiveRecordAdapter.new( # :adapter => "mysql", # :host => "localhost", # :username => "me", # :password => "secret", # :database => "activerecord" # ) def initialize(config={}) require "rubygems" require "activerecord" Persistence.class_eval <<-EOF class Feature < ::ActiveRecord::Base end class Category < ::ActiveRecord::Base end EOF ::ActiveRecord::Base.establish_connection(config) c = ::ActiveRecord::Base.connection tables = c.tables unless tables.member?("features") c.create_table(:features) do |t| t.column :feature, :string t.column :category, :string t.column :count, :integer end c.add_index(:features, [:category, :feature], :unique => true) end unless tables.member?("categories") c.create_table(:categories) do |t| t.column :category, :string t.column :count, :integer end c.add_index(:categories, :category, :unique => true) end end def increment_feature(feature, category) count = feature_count(feature, category) if count > 0 Feature.update_all(["count = ?", count + 1], { :feature => feature }) else Feature.create!(:feature => feature, :category => category.to_s.strip, :count => 1) end end def feature_count(feature, category) f = Feature.find(:first, :conditions => { :feature => feature, :category => category.to_s.strip }) f ? f.count : 0 end def increment_category(category) count = category_count(category) if count > 0 Category.update_all(["count = ?", count + 1], { :category => category }) else Category.create!(:category => category.to_s.strip, :count => 1) end end def category_count(category) c = Category.find(:first, :conditions => { :category => category.to_s.strip }) c ? c.count : 0 end def total_count Category.sum("count") end def categories Category.find(:all).map { |c| c.category } end end ## # A simple +Hash+ backed persistence store. This is the default persistence # for the various classifiers unless another implementation is provided. class InMemory def initialize @feature_count = Hash.new do |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = 0 } end @category_count = Hash.new { |h,k| h[k] = 0 } end def increment_feature(feature, category) @feature_count[feature][category] += 1 end def increment_category(category) @category_count[category] += 1 end def category_count(category) (@category_count[category] || 0).to_f end def feature_count(feature, category) if @feature_count.has_key?(feature) && @category_count.has_key?(category) @feature_count[feature][category].to_f else 0.0 end end ## # List all categories for this classifier. def categories @category_count.keys end ## # Returns the total number of items def total_count total = 0 @category_count.values.each do |v| total += v end total end end end ## # Pull all of the words out of a given doc +String+ and normalize them. # This is the default feature-extraction function used by all +Classifiers+. def self.get_words(doc) words = Set.new doc.split(/\s+/).each do |word| words << word.downcase if word.size > 2 && word.size < 20 end words end ## # A +Classifier+ is an object that is trained with blocks of text and # expected categories. After training, the +Classifier+ can classify # new blocks of text based on its training. class Classifier ## # A +Hash+ where thresholds can be set for a particular category. # These values are used by the +classify+ method. attr_reader :thresholds ## # Construct a new instance. # This requires a block that will accept a single item # and returns its features # == Parameters # * <tt>persistence</tt> - The persistence mechanism, defaults to in-memory # * <tt>block</tt> - A block that extracts features from a given block of text. If one isn't specified, the +get_words+ function is used. # == Persistence # By default (when no +persistence+ parameter is specified), classifiers store # their training data within in-memory +Hashes+. # However, for any decent corpus, this will quickly exceed the capacity of your # system. Therefore, the underlying persistence mechanism is separated from the # classification details. To use a different mechanism, provide a different # object as the +persistence+ parameter to handle the underlying details. # # This code comes with two built-in persistence implementations: # * <tt>Filtering::Persistence::InMemory</tt> # * <tt>Filtering::Persistence::ActiveRecordAdapter</tt> # # You can define your own persistence mechanism as long the the object # you provide implements the following "duck-type" interface: # * <tt>increment_feature(feature, category)</tt> # * <tt>feature_count(feature, category)</tt> # * <tt>increment_category(category)</tt> # * <tt>category_count(category)</tt> # * <tt>total_count()</tt> # * <tt>categories()</tt> # See one of the existing implementations for details. def initialize(persistence=nil, &block) @persistence = persistence || Filtering::Persistence::InMemory.new if block_given? @get_features_func = block else @get_features_func = lambda { |item| Filtering.get_words(item) } end @thresholds = {} @thresholds.default = 0 end ## # Returns the number of occurrences of a given +feature+ for # a given +category+. # == Example # classifier = Filtering::Classifier.new # # classifier.train("the quick brown fox jumps over the lazy dog", :good) # classifier.train("make quick money in the online casino", :bad) # # classifier.feature_count("quick", :good) #=> 1.0 # classifier.feature_count("quick", :bad) #=> 1.0 # classifier.feature_count("dog", :good) #=> 1.0 # classifier.feature_count("dog", :bad) #=> 0.0 def feature_count(feature, category) @persistence.feature_count(feature, category) end ## # Train the classifier by passing an +item+ and the expected +category+. # Features will be extracted from the +item+ using the block provided # in the constructor # == Parameters # * <tt>item</tt> - The block of text to train with # * <tt>category</tt> - The category to associate with this text (best done with a symbol) # == Example # classifier = Filtering::Classifier.new do |item| # Filtering.get_words(item) # end # classifier.train("the quick brown fox jumps over the lazy dog", :good) # classifier.train("make quick money in the online casino", :bad) def train(item, category) features = get_features(item) # increment the feature count features.each do |feature| increment_feature(feature, category) end # increment he category count increment_category(category) end ## # Returns the probably (between 0.0 and 1.0) of a feature # for a given category. Pr(feature | category) def feature_probability(feature, category) return 0 if category_count(category) == 0 feature_count(feature, category).to_f / category_count(category).to_f end ## # Returns the weighted probability of a feature for a given category # using the +prf+ function to calculate with the given # +weight+ and +assumed_prob+ variables (both of which have defaults) # == Parameters # * <tt>feature</tt> - The feature to calculate probability for # * <tt>category</tt> - The category to calculate probability # * <tt>prf</tt> - a probability function # * <tt>weight</tt> - defaults to 1.0 # * <tt>assumed_prob</tt> - defaults to 0.5 # * <tt>block</tt> - A block to calculate probability of a feature for a category # == Example # classifier = Filtering::Classifier.new # # classifier.train("the quick brown fox jumps over the lazy dog", :good) # classifier.train("make quick money in the online casino", :bad) # # prob = classifier.weighted_probability("money", :good) do |f, c| # classifier.feature_probability(f, c) # end.should # # #=> prob = 0.25 def weighted_probability(feature, category, weight=1.0, assumed_prob=0.5, &block) raise "You must provide a block" unless block_given? basic_probabilty = block.call(feature, category).to_f totals = 0 categories.each do |category| totals += feature_count(feature, category).to_f end ((weight * assumed_prob).to_f + (totals * basic_probabilty).to_f) / (weight + totals).to_f end ## # Classify a given +item+ based on training done by calls to the +train+ # method. # == Parameters # * <tt>item</tt> - A block of text to classify # * <tt>default</tt> - A default category if one cannot be determined # == Example # classifier = Filtering::Classifier.new # # classifier.train("Nobody owns the water", :good) # classifier.train("the quick rabbit jumps fences", :good) # classifier.train("buy pharmaceuticals now", :bad) # classifier.train("make quick money at the online casino", :bad) # classifier.train("the quick brown fox jumps", :good) # # classifier.classify("quick rabbit", :unknown) #=> :good # classifier.classify("quick money", :unknown) #=> :bad # classifier.classify("chocolate milk", :unknown) #=> :unknown def classify(item, default=nil) probs = {} probs.default = 0.0 max = 0.0 best = nil categories.each do |cat| probs[cat] = prob(item, cat).to_f if probs[cat] > max max = probs[cat] best = cat end end probs.each do |cat, prob| next if cat == best if probs[cat] * thresholds[best] > probs[best] return default end end best end private ## # Invokes the block given in the +initialize+ method to # extract features for the given +item+ def get_features(item) @get_features_func.call(item) end def increment_feature(feature, category) @persistence.increment_feature(feature, category) end def increment_category(category) @persistence.increment_category(category) end ## # Returns the number of items in a given category def category_count(category) @persistence.category_count(category) end ## # List all categories for this classifier. def categories @persistence.categories end ## # Returns the total number of items def total_count @persistence.total_count end end ## # Like the other classifiers you construct one, passing in a block # to extract features, train it and ask questions. This class uses # Bayes' Theorem to calculate the probability of a particular # category for a given document: # Pr(Category | Document) = Pr(Document | Category) * Pr(Category) / Pr(Document) # # This classifer is called "naive" because it assumes that the features of # a document are independent. This isn't strictly true, but can still provide # useful results nonetheless. # == Examples # c = Filtering::NaiveBayes.new # # c.train("Nobody owns the water", :good) # c.train("the quick rabbit jumps fences", :good) # c.train("buy pharmaceuticals now", :bad) # c.train("make quick money at the online casino", :bad) # c.train("the quick brown fox jumps", :good) # # c.prob("quick rabbit", :good) #=> ~ 0.156 # c.prob("quick rabbit", :bad) #=> ~ 0.050 class NaiveBayes < Classifier ## # Returns the probability of the category, i.e. Pr(Document|Category) def prob(item, category) cat_prob = category_count(category).to_f / total_count.to_f doc_prob = document_probability(item, category) doc_prob * cat_prob end ## # Determines the probability that a given document is # within a given category. private def document_probability(item, category) p = 1 get_features(item).each do |f| p *= weighted_probability(f, category) do |f, c| self.feature_probability(f, c).to_f end end p end end ## # Works like the other classifiers. Construct one, pass it a # block to extract features, train, and ask it questions. # # This classifer improves upon the +NaiveBayes+ by calculting the probability # of each feature, combines them and tests to see if the set is more or less # likely than a random set. # == Examples # c = Filtering::Fisher.new # # c.train("Nobody owns the water", :good) # c.train("the quick rabbit jumps fences", :good) # c.train("buy pharmaceuticals now", :bad) # c.train("make quick money at the online casino", :bad) # c.train("the quick brown fox jumps", :good) # # c.fisher_prob("quick rabbit", :good) #=> ~ 0.780 # c.fisher_prob("quick rabbit", :bad) #=> ~ 0.356 class Fisher < Classifier ## # A +Hash+ for setting minimums for a particular category. This # is used by the +classify+ method. attr_reader :minimums def initialize(persistence=nil, &block) super(persistence, &block) @minimums = {} @minimums.default = 0.0 end ## # Classify the given +item+. How the text is classified is affected # by any minimums set for a particular category via the +minimums+ # +Hash+ attribute. By default, the minimum for each category is set # to <tt>0.0</tt>. # == Parameters # * <tt>item</tt> The text block to classify # * <tt>default</tt> An optional category if one can't be determined. def classify(item, default=nil) best = default max = 0.0 categories.each do |cat| p = fisher_prob(item, cat).to_f if p > @minimums[cat] and p > max best = cat max = p end end best end ## # Returns the proportion of P(feature | category) relative to # sum of probabilities of _all_ categories for the given +feature+. # Like the other probability functions, this one assumes the classifier # has been trained with calls to the +train+ method. def prob(feature, category) fprob = feature_probability(feature, category) return 0 if fprob == 0 freq_sum = 0 categories.each { |cat| freq_sum += feature_probability(feature, cat) } fprob.to_f / freq_sum.to_f end ## # Multiplies the probabilities of each feature, applies # the natural log and multiplies by -2. Why? Beats the # hell out of me. def fisher_prob(item, category) p = 1 features = get_features(item).each do |f| p *= weighted_probability(f, category) do |f, c| self.prob(f, c) end.to_f end score = -2 * Math.log(p) inv_chi2(score, features.size * 2) end private ## # An mplementation of the inverse chi-square function # http://en.wikipedia.org/wiki/Inverse-chi-square_distribution def inv_chi2(chi, df) m = chi.to_f / 2.0 sum = term = Math.exp(-m) (1...df/2).each do |i| term *= m.to_f / i.to_f sum += term end [sum, 1.0].min end end end class String @@n_gram_length = 1 # These are copied uncritically from Lucas Carlson's Classifier library. @@stop_words = %w(a again all along are also an and as at but by came can cant couldnt did didn didnt do doesnt dont ever first from have her here him how i if in into is isnt it itll just last least like most my new no not now of on or should sinc so some th than this that the their then those to told too true try until url us were when whether while with within yes you youll) def self.n_gram_length=(newval) @@n_gram_length = newval end def self.stop_words=(newval) @@stop_words = newval end def self.stop_words @@stop_words end def self.add_stop_words(adds) @@stop_words += adds.map {|w| w.downcase} @@stop_words.uniq! end def self.remove_stop_words(removes) @@stop_words -= removes end def tokenise # Doing some regex massaging. # Replace single or double dashes w/a single space. Replace tildes w/spaces text = gsub(/(-{1,2}|~)/, ' ').downcase # Eat punctuation text.gsub!(/[^\w\s]/, '') # Change digits to placeholder text.gsub!(/\d/, '#') words = text.split.select {|w| w.length > 1 and not(@@stop_words.include?(w))} tokens = [] 0.upto(words.length) do |i| @@n_gram_length.downto(1) do |k| chunk = words[i, k] if chunk.length == k then # TODO?: keep from crossing obvious sentence boundaries (e.g., test for periods in elements other than chunk[-1]) tokens << chunk.map do |w| # puts(w) w.stem end.join('_') end end end return tokens # + words.map {|w| w.stem} end end
true
22f9831a9e07a57d30494968aceda6d5495c1285
Ruby
yast/zombie-killer
/lib/zombie_killer/eager_rewriter.rb
UTF-8
3,779
2.75
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "unparser" require "set" require "zombie_killer/rule" # Rewrite Zombies with their idiomatic replacements class EagerRewriter < Parser::TreeRewriter def self.s(name, *children) Parser::AST::Node.new(name, children) end def s(name, *children) self.class.s(name, *children) end OPS = s(:const, nil, :Ops) BUILTINS = s(:const, nil, :Builtins) Arg = Rule::Arg @rules = {} class << self attr_reader :rules end def self.r(**kwargs) rule = Rule.new(**kwargs) type = rule.from.type @rules[type] ||= [] @rules[type] << rule end [ [:lvasgn, :lvar], # a = b [:ivasgn, :ivar], # @a = @b [:cvasgn, :cvar], # @@a = @@b ].each do |xvasgn, xvar| [:+, :-, :*].each do |asop| r from: s(xvasgn, Arg, s(:send, s(xvar, Arg), asop, Arg)), # @ARG1 = @ARG2 + ARG3 to: ->(a, b, c) do # rubocop:disable Style/Lambda if a == b s(:op_asgn, s(xvasgn, a), asop, c) # @ARG1 += ARG3 end end end end INFIX = { add: :+, subtract: :-, multiply: :*, divide: :/, modulo: :%, bitwise_and: :&, bitwise_or: :|, bitwise_xor: :^, less_than: :<, less_or_equal: :<=, greater_than: :>, greater_or_equal: :>= }.freeze INFIX.each do |prefix, infix| r from: s(:send, OPS, prefix, Arg, Arg), # Ops.add(Arg, ARG2) to: ->(a, b) { s(:send, a, infix, b) } # Arg + ARG2 end r from: s(:send, BUILTINS, :size, Arg), # Builtins.size(Arg) to: ->(a) { s(:send, a, :size) } # Arg.size r from: s(:send, s(:send, Arg, :size), :>, s(:int, 0)), # Arg.size > 0 to: ->(a) { s(:send, s(:send, a, :empty?), :!) } # !Arg.empty? r from: s(:send, s(:send, Arg, :size), :!=, s(:int, 0)), # Arg.size != 0 to: ->(a) { s(:send, s(:send, a, :empty?), :!) } # !Arg.empty? r from: s(:send, s(:send, Arg, :size), :==, s(:int, 0)), # Arg.size == 0 to: ->(a) { s(:send, a, :empty?) } # Arg.empty? r from: s(:send, s(:send, Arg, :size), :<=, s(:int, 0)), # Arg.size <= 0 to: ->(a) { s(:send, a, :empty?) } # Arg.empty? r from: s(:send, s(:send, Arg, :size), :<, s(:int, 1)), # Arg.size < 1 to: ->(a) { s(:send, a, :empty?) } # Arg.empty? def self.sformat_replacement1(format_literal, value) verbatims = format_literal.split("%1", -1) return nil unless verbatims.size == 2 s(:dstr, s(:str, verbatims[0]), value, s(:str, verbatims[1])) end r from: s(:send, BUILTINS, :sformat, s(:str, Arg), Arg), # Builtins.sformat("...", val) to: ->(fmt, val) { sformat_replacement1(fmt, val) } # Does not improve readability much, fails on nil. Use foo&.each ? # r from: s(:send, BUILTINS, :foreach, Arg), # to: ->(a) { s(:send, a, :each) } def unparser_sanitize(code_s) # unparser converts "foo#{bar}baz" # into "#{"foo"}#{bar}#{"baz"}" # so this undoes the escaping of the litetrals code_s.gsub(/ \# \{" ( [^"#]* ) "\} /x, '\1') end def replace_node(old_node, new_node) # puts "OLD #{old_node.inspect}" # puts "NEW #{new_node.inspect}" source_range = old_node.loc.expression unp = Unparser.unparse(new_node) unp = unparser_sanitize(unp) # puts "UNP #{unp.inspect}" replace(source_range, unp) new_node end def process(node) node = super(node) return if node.nil? trules = self.class.rules.fetch(node.type, []) trules.find do |r| replacement = r.match(node) node = replace_node(node, replacement) if replacement end node end end
true
5ed43a899452e5c8a98eb5f1bd59fe41ead8c7f8
Ruby
AllPurposeName/runewords-api
/lib/tasks/import_data.rake
UTF-8
1,777
2.921875
3
[]
no_license
require 'yaml' require 'colorize' namespace :data do desc 'Import all the Runeword YAML files into models in our DB.' # NOTE: # This is only valid when run after dropping and re-generating the DB # since the ids need to start from 1 so that foreign keys will match up task import: :environment do runes_file = "#{Rails.root}/lib/assets/yml/runes.yml" props_file = "#{Rails.root}/lib/assets/yml/props.yml" item_types_file = "#{Rails.root}/lib/assets/yml/item_types.yml" runewords_file = "#{Rails.root}/lib/assets/yml/runewords.yml" runes_yml = YAML.load_file(runes_file) props_yml = YAML.load_file(props_file) item_types_yml = YAML.load_file(item_types_file) runewords_yml = YAML.load_file(runewords_file) @klass = Rune runes_yml['runes'].each(&populate) @klass = Property props_yml['properties'].each(&populate) @klass = ItemType item_types_yml['itemTypes'].each(&populate) runewords_yml['runewords'].each do |id, data| runeword = Runeword.create!(id: id, name: data['name'], character_level: data['clvl'], ladder_only: data['ladderOnly']) runeword.runes << data['runes'].values.map { |r| Rune.find(r) } runeword.item_types << data['itemTypes'].values.map { |i| ItemType.find(i) } runeword.properties << data['properties'].values.map { |p| Property.find(p) } puts_created(runeword) end end def populate proc do |id, data| data['id'] = id k = @klass.create!(data) puts_created(k) end end def puts_created(obj) puts "Created #{obj.class.to_s.colorize(:light_black)} #{obj.id} name: #{obj.name}" end end
true
5121ea959897acb8eb8d1dc7fb80decf4d4c70fd
Ruby
zare926/activerecord_lessons
/main.rb
UTF-8
1,024
2.6875
3
[]
no_license
require 'active_support/all' require "active_record" # ppはプリティープリント、オブジェクトをわかりやすく表現するrubyのライブラリ require 'pp' # 時間の設定、決まり文句ぐらいで覚える Time.zone_default = Time.find_zone! 'Tokyo' ActiveRecord::Base.default_timezone = :local # DBの読み込み ActiveRecord::Base.establish_connection( "adapter" => "sqlite3", "database" => "./myapp.db" ) # Association # User -> Comments class User < ActiveRecord::Base has_many :comments,dependent: :destroy end class Comment < ActiveRecord::Base belongs_to :user end User.delete_all User.create(name:"tanaka", age:19) User.create(name:"takahashi", age:12) User.create(name:"murata", age:24) User.create(name:"suzuki", age:77) User.create(name:"okazaki", age:10) Comment.delete_all Comment.create(user_id:1, body: "hello-1") Comment.create(user_id:1, body: "hello-2") Comment.create(user_id:2, body: "hello-3") User.find(1).destroy pp Comment.select("id, user_id, body").all
true
d0294a23eae1e9f593b05f9af5afa8b090adcb1f
Ruby
karolinee/University
/Programowanie obiektowe/lista8/zad3.rb
UTF-8
618
3.640625
4
[]
no_license
class Jawna def initialize(napis) @napis = napis end def zaszyfruj(klucz) kod = "" @napis.each_char { |i| kod << klucz[i]} return Zaszyfrowane.new(kod) end def to_s "Napis jawny: " + @napis end end class Zaszyfrowane def initialize(napis) @napis = napis end def odszyfruj(klucz) kod = "" @napis.each_char { |i| kod << klucz.key(i) } return Jawna.new(kod) end def to_s "Napis zaszyfrowany: " + @napis end end j = Jawna.new('ruby') puts j klucz = {'a'=>'b', 'b'=>'r', 'r'=>'y', 'y'=> 'u', 'u'=>'a'} z = j.zaszyfruj(klucz) puts z puts z.odszyfruj(klucz)
true
eb4cff09d2fcd8f5d48620a42a83973dfed1cf15
Ruby
ShanaLMoore/project-euler-multiples-3-5-e-000
/lib/multiples.rb
UTF-8
271
3.46875
3
[]
no_license
# Enter your procedural solution here! def collect_multiples(limit) multiples = [] for num in 1 ... limit if (num % 3 == 0) || (num % 5 == 0) multiples << num end end multiples end def sum_multiples(limit) collect_multiples(limit).inject(:+) end
true
19e4e3eca60acb6afbaa08bd517e254d6b4b951d
Ruby
venkatd/compute
/lib/compute/computation.rb
UTF-8
857
2.8125
3
[ "MIT" ]
permissive
module Compute class Computation attr_accessor :property def initialize(model, property, &block) @model = model @property = property @proc = Proc.new(&block) end def dependencies @dependencies ||= calculate_dependencies(@proc) end def needs_update?(changed_properties) common_changes = changed_properties.map(&:to_sym) & @dependencies common_changes.count > 0 end def execute(record) source_values = source_values(record) destination_result = record.instance_exec(*source_values, &@proc) record.send(@property.to_s + '=', destination_result) end private def calculate_dependencies(proc) proc.parameters.map { |arg| arg[1] } end def source_values(record) @dependencies.map { |property| record.send(property) } end end end
true
9c7319a52325d0bf7ad4ac2f94e11c87efcdaaa5
Ruby
reactormonk/magic_search
/cards/lib/magic_cards.rb
UTF-8
1,818
2.8125
3
[]
no_license
require 'nokogiri' require 'mana_symbols' module MagicCards class Rules def initialize(xml) @xml = xml end def each(&block) enum_for(:to_s, &block) end def rules @xml.xpath('./rule') end def to_a rules.map(&:text) end def by_no rules.group_by {|e| e['no']}.map {|_,e| e.map(&:text)} end def to_s by_no.map {|e| e.join(", ")}.join("\n") end end class Card def self.parse(xml) card = new(xml) if sub_xml = xml.xpath('./multi').first card.other_card = sub_card = new(sub_xml) sub_card.other_card = card sub_card.multi = card.multi = sub_xml['type'] end [card, sub_card].compact end attr_reader *%w(name supertype type subtype rules editions power toughness cost).map(&:to_sym) attr_accessor :other_card, :multi def initialize(xml_node) @name = xml_node.xpath('./name').text @type = xml_node.xpath('./typelist/type[@type="card"]').map(&:text) @subtype = xml_node.xpath('./typelist/type[@type="sub"]').map(&:text) @supertype = xml_node.xpath('./typelist/type[@type="super"]').map(&:text) @power = Integer(xml_node.xpath('./pow').text) rescue nil @toughness = Integer(xml_node.xpath('./tgh').text) rescue nil @rules = Rules.new(xml_node.xpath('./rulelist')) cost = xml_node.xpath('./cost').text @cost = ManaSymbols::parse(cost) unless cost.empty? end def colors @cost ? @cost.colors : Set.new end def id name.gsub(/[^[[:word:]][[:space:]]]/, '') end end def self.populate file_name = File.expand_path "../data/cards.xml", File.dirname(__FILE__) ::Nokogiri::XML(File.read(file_name)).xpath('//card').flat_map do |xml| Card.parse(xml) end end end
true
548a31b0472da4e9eb96deb36c901b890eaf96c6
Ruby
NilsLoewe/archive
/versuche/leo-v1/app/models/objective.rb
UTF-8
2,302
2.640625
3
[]
no_license
# == Schema Information # # Table name: objectives # # id :integer not null, primary key # title :string(255) # description :text # category_id :integer # created_at :datetime not null # updated_at :datetime not null # user_id :integer # status :string(255) # sprint_end :date # sprint_start :date # duration :integer # sprinttitle :string(255) # archive :boolean # parked :boolean # simple :boolean # class Objective < ActiveRecord::Base attr_accessible :description, :title, :category_id, :status, :duration, :sprint_start, :sprinttitle, :simple, :archive, :parked default_scope order('sprint_end ASC') scope :active, -> { where(archive: false, parked: false) } scope :done, -> { where(archive: true) } scope :parked, -> { where(parked: true) } after_create :set_defaults belongs_to :category delegate :user, :to => :category, :allow_nil => true has_many :tasks, dependent: :destroy, :as => :plan validates :title, presence: true, length: { maximum: 50 } validates :category_id, presence: true STATES = %w{ planning sprint_running sprint_finished } STATES.each do |status| define_method("#{status}?") do self.status == status end define_method("#{status}!") do self.update_attribute(:status, status) end end def unfinished_tasks_in_current_sprint? self.tasks.progress.unfinished.count > 0 end def finish_sprint! self.tasks.progress.each do |t| t.archive! end self.planning! end def days_left ((self.sprint_start + self.duration) - Date.today).to_i end def update_sprint_end self.update_attribute(:sprint_end, (self.sprint_start + self.duration)) end def unfinished_tasks self.tasks.unfinished.count end def unfinished_tasks_size self.tasks.unfinished.sum(:size) end def week_start self.user.week_start end def color self.category.color end private def set_defaults self.status = "planning" self.sprint_end = Date.today self.update_attribute(:simple, true) self.update_attribute(:parked, false) self.update_attribute(:archive, false) #self.update_attribute(:sprint_end, (self.sprint_start + 9999)) end end
true
a3f52a28787c698c51cbd578642cbed68345f1ee
Ruby
jonathansayer/chess
/app/services/convert_coordinates.rb
UTF-8
1,336
3.75
4
[]
no_license
class ConvertCoordinates @conversion_hash = {'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8 } def self.to_numerical_coords *positions coordinates = [] self.convert_to_x_and_y positions, coordinates return coordinates.first if coordinates.length == 1 coordinates end def self.to_alphabetical_coords *coords position_array = [] self.convert_to_coords_string coords, position_array return position_array.first if position_array.length == 1 position_array end private def self.convert_to_x_and_y positions, array positions.each do |position| split_position = position.split(//) x = @conversion_hash[split_position.first] y = split_position.last.to_i array.push([x,y]) end end def self.convert_to_coords_string coords, array coords.each do |coordinate| self.first_number_to_letter coordinate array.push(@letter + coordinate.last.to_s) end end def self.first_number_to_letter coords @conversion_hash.each do |key,value| if value == coords.first @letter = key break end end end end
true
4ab0002797ddbe4901619e1b5a8b8fccf8271ccd
Ruby
ashcode09/takeaway-challenge
/lib/order.rb
UTF-8
579
3.015625
3
[]
no_license
require_relative 'checkout' class Order attr_accessor :order_list, :menu_list include Checkout def initialize @menu_list = {"Bottle of Water" => 3.08, "Disney Themed Napkins (x5)" => 50, "Carbonara" => 0.4, "Ice cream" => 0.48, "Happiness" => 0} @order_list = [] end def print_menu menu_list.each do |dish_key, dish_price| "#{dish_key}: £#{dish_price}" end end def add_dish(quantity, dish_key) quantity.times do order_list << menu_list.select do |k| k == dish_key end end end def view_order order_list end end
true
92e650e2e45d23d15dcc9576c0ab49f4bd967188
Ruby
episodic/episodic-platform-ruby
/lib/episodic/platform/exceptions.rb
UTF-8
2,847
2.8125
3
[ "MIT" ]
permissive
module Episodic module Platform # # Abstract super class of all Episodic::Platform exceptions # class EpisodicPlatformException < StandardError end class FileUploadFailed < EpisodicPlatformException end # # An execption that is raised as a result of the response content. # class ResponseError < EpisodicPlatformException attr_reader :response # # Constructor # # ==== Parameters # # message<String>:: The message to include in the exception # response<Episodic::Platform::HTTPResponse>:: The response object. # def initialize(message, response) @response = response super(message) end end # # There was an unexpected error on the server. . # class InternalError < ResponseError end # # The API Key wasn't provided or is invalid or the signature is invalid. # class InvalidAPIKey < ResponseError end # # The requested report could not be found. Either the report token is invalid or the report has expired and is no longer available. # class ReportNotFound < ResponseError end # # The request failed to specifiy one or more of the required parameters to an API method. # class MissingRequiredParameter < ResponseError end # # The request is no longer valid because the expires parameter specifies a time that has passed. # class RequestExpired < ResponseError end # # The specified object (i.e. show, episode, etc.) could not be found. # class NotFound < ResponseError end # # API access for the user is disabled. # class APIAccessDisabled < ResponseError end # # The value specified for a parameter is not valid. # class InvalidParameters < ResponseError # # Constructor. Override to include inforation about the invalid parameter(s). # # ==== Parameters # # message<String>:: The message to include in the exception # response<Episodic::Platform::HTTPResponse>:: The response object. # invalid_parameters<Object>:: This is either a Hash or an Array of hashes if there is more than one invalid parameter. # def initialize(message, response, invalid_parameters) if (invalid_parameters) invalid_parameters["invalid_parameter"] = [invalid_parameters["invalid_parameter"]] if invalid_parameters["invalid_parameter"].is_a?(Hash) # Append to the message invalid_parameters["invalid_parameter"].each do |ip| message << "\n#{ip['name']}: #{ip['content']}" end end super(message, response) end end end end
true
5255c9fe5b035666202ab964065a601487d586e0
Ruby
falchek/headfirst_ruby
/chapter2/vehicle_methods.rb
UTF-8
750
3.65625
4
[]
no_license
# These methods are placed in the top-level execution environment # That means they're called without the dot operate. def accelerate puts "Stepping on the gas" puts "Speeding up!" end def sound_horn puts "Pressing the horn button" puts "Beep beep!" end def use_headlights(brightness = "low-beams") puts "Turning on #{brightness} headlights" puts "Watch out for deer!" end def start_engine puts "Starting the engine! Vroommm vroooooommmm!!" end def stop_engine puts "Stopping engine... " end def mileage(miles_driven, gas_used) if gas_used == 0 return 0.0 end miles_driven / gas_used end use_headlights stop_engine start_engine sound_horn accelerate use_headlights("high-beam") stop_engine
true
084d03410ce78f5de48f343c0bff0c548252845c
Ruby
CariWest/udacity-projects
/rbnd-toycity-part1-master/lib/app.rb
UTF-8
3,494
3.625
4
[]
no_license
require 'json' path = File.join(File.dirname(__FILE__), '../data/products.json') file = File.read(path) products_hash = JSON.parse(file) # Print today's date puts "Today's Date: #{Time.now.strftime("%D")}" puts " _ _ " puts " | | | | " puts " _ __ _ __ ___ __| |_ _ ___| |_ ___ " puts "| '_ \\| '__/ _ \\ / _` | | | |/ __| __/ __|" puts "| |_) | | | (_) | (_| | |_| | (__| |_\\__ \\" puts "| .__/|_| \\___/ \\__,_|\\__,_|\\___|\\__|___/" puts "| | " puts "|_| " # For each product in the data set: # Print the name of the toy # Print the retail price of the toy # Calculate and print the total number of purchases # Calculate and print the total amount of sales # Calculate and print the average price the toy sold for # Calculate and print the average discount (% or $) based off the average sales price def calculate_avg(prices) num_prices = prices.count calculate_total(prices) / num_prices end def calculate_total(prices) prices.reduce(0) { |sum, price| sum + price} end products_hash["items"].each do |product| actual_price = product["full-price"].to_f purchases = product["purchases"] purchase_prices = purchases.map { |purchase| purchase["price"].to_f } discounts = purchases.map { |purch| actual_price - purch["price"].to_f } total_sales = calculate_total(purchase_prices) average_price = calculate_avg(purchase_prices) average_discount = calculate_avg(discounts) puts "#{product["title"]}" puts "Retail Price: $#{actual_price}" puts "Purchase Count: #{purchases.count}" puts "Total Sales: $#{total_sales}" puts "Average Price: $#{average_price.round(2)}" puts "Average Discount: $#{average_discount.round(2)}" puts end puts " _ _ " puts "| | | | " puts "| |__ _ __ __ _ _ __ __| |___ " puts "| '_ \\| '__/ _` | '_ \\ / _` / __|" puts "| |_) | | | (_| | | | | (_| \\__ \\" puts "|_.__/|_| \\__,_|_| |_|\\__,_|___/" puts # For each brand in the data set: # Print the name of the brand # Count and print the number of the brand's toys we stock # Calculate and print the average price of the brand's toys # Calculate and print the total revenue of all the brand's toy sales combined brands_hash = {} products_hash["items"].each do |product| brand = product["brand"] # If brand doesn't exist in hash yet, create # the hash to collect brand data unless !!brands_hash[brand] brands_hash[brand] = { "total_toys_stocked" => 0, "toy_prices" => [], "total_revenue" => 0 } end product_purchases = product["purchases"].map { |purch| purch["price"].to_f } # Populate the brand data brands_hash[brand]["total_toys_stocked"] += 1 brands_hash[brand]["toy_prices"] << product["full-price"].to_f brands_hash[brand]["total_revenue"] += calculate_total(product_purchases) end brands_hash.each do |brand| brand_name = brand.first brand_data = brand.last total_toys_stocked = brand_data["total_toys_stocked"] average_toy_price = calculate_avg(brand_data["toy_prices"]) total_revenue = brand_data["total_revenue"] puts "#{brand_name}" puts "Total Toys Stocked: #{total_toys_stocked}" puts "Average Price: #{average_toy_price.round(2)}" puts "Total Revenue: #{total_revenue.round(2)}" puts end
true
7a9b3892a1330d14a6b39c9ded4176afd40eb8c1
Ruby
AllPurposeName/ScriptHub
/load_task.rake
UTF-8
4,338
2.671875
3
[]
no_license
require 'faker' require "capybara/poltergeist" require 'pry' require 'launchy' desc "simulate load against HubStub app" task :load_test do 4.times.map { |i| Thread.new {Raker.new(i).new_users}; Thread.new {Raker.new(i).admin_surfing}; Thread.new {Raker.new(i).user_adventures}; Thread.new {Raker.new(i).add_random_ticket}; Thread.new {Raker.new(i).user_adventures}; Thread.new {Raker.new(i).add_random_ticket} }.map(&:join) end class Raker attr_reader :iteration, :session def initialize(iteration) @iteration = iteration @session = Capybara::Session.new(:poltergeist) end #admin surfing hits admin base end points #user adventures utilizes the "adventure" randomization feature and adds tickets to a cart #new users creates, logs out, and logs back in users def admin_surfing puts "starting admin surfing" as_admin loop do session.visit(admin_url.root) session.visit(admin_url.events) session.visit(admin_url.categories) session.visit(admin_url.users) session.visit(admin_url.venue) puts "visited admin endpoints, iteration: #{iteration}" end end def user_adventures puts "starting user adventures" loop do new_user adventure add_ticket_to_cart end end def new_users puts "starting creating new users" loop do new_user end end def add_random_tickets puts "starting adding random tickets" loop do number_of_tickets = rand(1..3) number_of_tickets.times do session.visit(url(rand(1..15)).event_page) add_ticket_to_cart end puts "#{number_of_tickets} ticket(s) added to unassigned cart, iteration: #{iteration}" end end private def new_user name = "#{Faker::Name.name} #{Faker::Name.suffix}" email = Faker::Internet.email password = Faker::Internet.password(8) sign_up(name, email, password) log_out log_in(email, password) puts "User #{name} signed up on #{session.current_path}, iteration: #{iteration}" puts "#{session.current_path}" end def adventure session.visit(url.root) session.click_link_or_button("Adventure") end def add_ticket_to_cart if session.has_css?("td.vert-align") click_cart puts "added a random ticket from #{session.current_path}" else puts "no tickets left on #{session.current_path}" end end def click_cart session.within("table.event-tickets") do session.all("a").sample.click end end def sign_up(name, email, password) session.visit(url.log_in) session.click_link_or_button("here") session.fill_in("user[full_name]", with: (name)) session.fill_in("user[display_name]", with: (name)) session.fill_in("user[email]", with: (email)) session.fill_in("user[street_1]", with: Faker::Address.street_address) session.fill_in("user[street_2]", with: Faker::Address.building_number) session.fill_in("user[city]", with: ("#{Faker::Address.city_prefix} #{Faker::Address.city_suffix}")) session.fill_in("user[zipcode]", with: (Faker::Address.zip)) session.fill_in("user[password]", with: (password)) session.fill_in("user[password_confirmation]", with: (password)) session.click_link_or_button("Create my account!") end def as_admin email = "[email protected]" password = "password" log_in(email, password) end def log_out session.visit(url.log_out) end def log_in(email, password) session.visit(url.log_in) session.fill_in("session[email]", with: (email)) session.fill_in("session[password]", with: (password)) session.click_link_or_button("Log in") end def domain "http://localhost:3000" end def url(event_id=1) OpenStruct.new(root: "#{domain}", events_index: "#{domain}/events", event_page: "#{domain}/events/#{event_id}", tickets_index: "#{domain}/tickets", log_out: "#{domain}/logout", log_in: "#{domain}/login") end def admin_url OpenStruct.new(root: "#{domain}/admin", events: "#{domain}/admin/events", venues: "#{domain}/admin/venues", categories: "#{domain}/admin/categories", users: "#{domain}/admin/users") end end
true
46db1b258082c5f08e8aa2ded5c0facefb80238f
Ruby
ARERA-it/inviti
/app/helpers/calendario_helper.rb
UTF-8
450
2.609375
3
[ "MIT" ]
permissive
module CalendarioHelper def cell_classes(cal_date) arr = [] arr << (cal_date.outer ? 'outer' : 'inner') arr << (cal_date.workday ? 'workday' : 'non_workday') arr << (cal_date.date==Date.today ? 'today' : nil) [:top, :bottom, :left, :right].each do |direction| arr << ("#{direction}_line" if cal_date.send("#{direction}_line")) end arr << (cal_date.holiday? ? 'holiday' : nil) arr.compact.join(" ") end end
true
d1a1b8de9537f85e4a1c49bcbd994a58774b80ad
Ruby
blee2125/top-companies-y-combinator-cli-gem
/lib/top_yc_companies/scraper.rb
UTF-8
531
2.921875
3
[ "MIT" ]
permissive
class TopYcCompanies::Scraper #retrieves the website to scrape def list_page Nokogiri::HTML(open("https://www.ycombinator.com/topcompanies/")) end #scrape_page is responsible for scraping all of the company data def scrape_page self.list_page.css("tbody#main-companies tr") end #make_company iterates through each company and passes the data to the new_company method in the Company class def make_company scrape_page.each do |c| TopYcCompanies::Company.new_company(c) end end end
true
96d1302a005be56dfcc028f3d370025eb2b2fa56
Ruby
mongodb/mongoid
/lib/mongoid/matcher/size.rb
UTF-8
1,377
2.84375
3
[ "MIT" ]
permissive
# rubocop:todo all module Mongoid module Matcher # In-memory matcher for $size expression. # # @see https://www.mongodb.com/docs/manual/reference/operator/query/size/ # # @api private module Size # Returns whether a value satisfies a $size expression. # # @param [ true | false ] exists Not used. # @param [ Numeric ] value The value to check. # @param [ Integer | Array<Object> ] condition The $size condition # predicate, either a non-negative Integer or an Array to match size. # # @return [ true | false ] Whether the value matches. # # @api private module_function def matches?(exists, value, condition) case condition when Float raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}" when Numeric if condition < 0 raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}" end else raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}" end if Array === value value.length == condition else false end end end end end
true
a41300165b0c37b69e12788c6713b0d3754c41b1
Ruby
LadyDianah/ruby_class
/class1.rb
UTF-8
118
2.875
3
[]
no_license
# prints out name puts "Iam Dianah" puts 2+5 def name() puts "enter your name" name=gets puts name end puts name()
true
38aac091b6083a990b3dc1e45cfb214ca04e455c
Ruby
henderea/epg_util
/lib/epg/plugin/stats.plugin.rb
UTF-8
4,617
2.734375
3
[ "MIT" ]
permissive
require 'everyday-plugins' include EverydayPlugins require 'everyday-cli-utils' EverydayCliUtils.import :histogram, :kmeans, :maputil require 'io/console' module EpgUtil class Stats extend Plugin register(:command, id: :path_stats, parent: :path, name: 'stats', aliases: %w(stat), short_desc: 'stats', desc: 'print out the path of the file for the stats module') { puts __FILE__ } register :command, id: :stats, parent: nil, name: 'stats', aliases: %w(stat), short_desc: 'stats SUBCOMMAND ARGS...', desc: 'a set of statistics-related operations' register(:helper, name: 'get_data', parent: :stats) { data = [] if options[:file].nil? val = nil i = 0 begin begin val = $stdin.gets.chomp if val.length > 0 data[i] = val.to_f i += 1 end rescue # ignored end end until val.nil? || val.length <= 0 || $stdin.eof? else if File.exist?(options[:file]) data = IO.readlines(options[:file]).filtermap { |v| begin f = v.chomp f.length == 0 || (f =~ /^\d+(\.\d+)?$/).nil? ? false : f.to_f rescue false end } else puts "File '#{options[:file]}' does not exist!" exit 1 end end data } register(:command, id: :stats_histogram, parent: :stats, name: 'histogram', aliases: %w(hist), short_desc: 'histogram', desc: 'create a histogram in the terminal') { data = get_data rows, cols = IO.console.winsize ks = options[:k_value].nil? ? data.nmeans : data.kmeans(options[:k_value]) puts data.histogram(ks, options[:width] || cols, options[:height] || rows - 3) } register :flag, name: :file, parent: :stats_histogram, aliases: %w(-f), type: :string, desc: 'use a file instead of stdin' register :flag, name: :k_value, parent: :stats_histogram, aliases: %w(-k), type: :numeric, desc: 'use a specific k value instead of n-means' register :flag, name: :width, parent: :stats_histogram, aliases: %w(-w), type: :numeric, desc: 'specify a width for the histogram' register :flag, name: :height, parent: :stats_histogram, aliases: %w(-h), type: :numeric, desc: 'specify a height for the histogram' register(:command, id: :stats_outliers, parent: :stats, name: 'outliers', aliases: %w(out), short_desc: 'outliers', desc: 'calculate the outliers of a set of numbers') { data = get_data options[:sensitivity] = 0.5 if options[:sensitivity].nil? options[:delimiter] = ', ' unless options[:one_per_line] || options[:delimiter] ol = data.outliers(options[:sensitivity], options[:k_value]).sort puts ol.join("#{options[:delimiter]}#{options[:one_per_line] ? "\n" : ''}") } register :flag, name: :file, parent: :stats_outliers, aliases: %w(-f), type: :string, desc: 'use a file instead of stdin' register :flag, name: :one_per_line, parent: :stats_outliers, aliases: %w(-1), type: :boolean, desc: 'put each outlier on a separate line' register :flag, name: :delimiter, parent: :stats_outliers, aliases: %w(-d), type: :string, desc: 'use a specific delimiter to separate the outliers' register :flag, name: :sensitivity, parent: :stats_outliers, aliases: %w(-s), type: :numeric, desc: 'use a specific sensitivity level (0-1)' register :flag, name: :k_value, parent: :stats_outliers, aliases: %w(-k), type: :numeric, desc: 'use a specific k value instead of n-means' register(:command, id: :stats_means, parent: :stats, name: 'means', aliases: %w(nmeans kmeans), short_desc: 'means', desc: 'calculate the n-means or k-means of a set of numbers') { data = get_data options[:delimiter] = ', ' unless options[:one_per_line] || options[:delimiter] ks = options[:k_value].nil? ? data.nmeans : data.kmeans(options[:k_value]) puts ks.join("#{options[:delimiter]}#{options[:one_per_line] ? "\n" : ''}") } register :flag, name: :file, parent: :stats_means, aliases: %w(-f), type: :string, desc: 'use a file instead of stdin' register :flag, name: :one_per_line, parent: :stats_means, aliases: %w(-1), type: :boolean, desc: 'put each outlier on a separate line' register :flag, name: :delimiter, parent: :stats_means, aliases: %w(-d), type: :string, desc: 'use a specific delimiter to separate the outliers' register :flag, name: :k_value, parent: :stats_means, aliases: %w(-k), type: :numeric, desc: 'use a specific k value instead of n-means' end end
true
dd0e37c20b6d2dbeff219d03714ad0160ddea058
Ruby
gprashanthkumar/examtracker
/vendor/plugins/harbinger-rails-extensions/plugin_utils.rb
UTF-8
2,209
2.875
3
[]
no_license
require 'fileutils' module PluginUtils class ResourceInstallation attr_reader :source def initialize(src, dest, opts = {}) @source = src @destination = dest @options = opts end def overwrites? @options[:overwrite] end def message @options[:message] end protected def install_by_method(src_root, dest_root, meth) file_src = File.join(src_root, @source) file_dest = File.join(dest_root, @destination) file_chk = File.join(file_dest, File.basename(file_src)) if !overwrites? return(nil) if File.exist?(file_chk) end puts(message) if !message.nil? FileUtils.send(meth.to_sym, file_src, file_dest, {:verbose => true}) end end class FileInstallation < ResourceInstallation def install!(src_root, dest_root) install_by_method(src_root, dest_root, :cp) end end class DirectoryInstallation < ResourceInstallation def install!(src_root, dest_root) install_by_method(src_root, dest_root, :cp_r) end end class Installer attr_reader :source_root, :destination_root def initialize(plugin_name) @source_root = File.expand_path(File.join(RAILS_ROOT, "vendor/plugins/#{plugin_name}")) @destination_root = File.expand_path(RAILS_ROOT) @files_to_copy = [] @directories_to_copy = [] yield self if block_given? end def install_file(src, dest, opts={}) @files_to_copy.push(FileInstallation.new(src, dest, opts)) end def install_directory(src, dest, opts={}) @directories_to_copy.push(DirectoryInstallation.new(src, dest, opts)) end def directories_to_install @directories_to_copy.map(&:source) end def files_to_install @files_to_copy.map(&:source) end def installation_of(src) @files_to_copy.detect { |fi| fi.source == src } end def installation_of_directory(src) @directories_to_copy.detect { |di| di.source == src } end def install! @files_to_copy.each { |fi| fi.install!(@source_root, @destination_root) } @directories_to_copy.each { |di| di.install!(@source_root, @destination_root) } end end end
true
b3357793130c394be889eaf11c7f9e518fb17109
Ruby
bother7/rails-project-mode-web-071717
/app/models/user_team.rb
UTF-8
1,741
2.796875
3
[ "MIT" ]
permissive
class UserTeam < ApplicationRecord has_many :player_user_teams has_many :players, through: :player_user_teams belongs_to :user, optional: true validates :name, presence:true, uniqueness: true validate :unique? validate :totalsalary def unique? self.errors[:players] << "need to be unique" if self.players != self.players.uniq end def matches Match.where("hometeam_id = ? OR awayteam_id = ?", self.id, self.id) end def salary sum = 0 players.each do |player| sum += player.contract end sum end def totalsalary self.errors[:salary] << " is Over Team Budget by #{self.salary - 155}" unless (self.salary <= 155 || self.user_id == nil) end def win_loss_record homegames = self.matches.select {|match| match.hometeam_id == self.id} awaygames = self.matches.select {|match| match.awayteam_id == self.id} awayrecord = [] homerecord = [] string = "" homerecord = homegames.map do |game| if (game.home_goals > game.away_goals) "win" elsif (game.home_goals < game.away_goals) "loss" else "tie" end end awayrecord = awaygames.map do |game| if (game.away_goals > game.home_goals) "win" elsif (game.away_goals < game.home_goals) "loss" else "tie" end end totalrecord = homerecord + awayrecord wins = totalrecord.select {|result| result == "win"} self.wins = wins.size losses = totalrecord.select {|result| result == "loss"} self.losses = losses.size ties = totalrecord.select {|result| result == "tie"} self.ties = ties.size self.save string = "#{wins.size} Wins - #{losses.size} Losses - #{ties.size} Ties" end end
true
b1b236262031d66eaa17f5476b85e69237d2e911
Ruby
IdleScV/Notes
/MOD 1 Notes/ActiveRecord/intro_active_record.rb
UTF-8
2,654
3.125
3
[]
no_license
Things we need for active record to work.. #? Additional documentation... #* https://guides.rubyonrails.org/active_record_basics.html#update #* http://jamesponeal.github.io/projects/active-record-sheet.html in GEM sqlite // This is just a database. It can be any database #! rake //These are also neccesary #! activerecord #! sinatra-activerecord in Environemnet require 'require_all' require_all'./lib' require_all './db' # // MIGRATE, They allow us to manage the databse structure # // MODELS, they allow us to manage the database data # // class User < ActiveRecord::Base #! User inherits all the methods of ActiveRecord::Base end As long as we have a database table called User, these functions bellow would work. Also, when we use the class User, ActiveRecord automatically looks at the *Users*. it is pluralized. User.all Returns... All instances User.new() function... creates an item inside of ruby world User.create() function... Creates an item inside of the database and also in the ruby world. #? #.save function... Saves the instance inside of the User.find_by(username: 'coffee') returns... coffee instance from the database User.last Returns... Last instance in the database. #// # ! Some More methods... :highest_rating returns the rating of the TV show with the highest rating ::most_popular_show returns the name of the TV show with the highest rating ::lowest_rating returns the rating of the TV show with the lowest rating ::least_popular_show returns the name of the TV show with the lowest rating ::ratings_sum returns the sum of all the ratings of all the tv shows ::popular_shows returns an array of all of the shows with a rating above 5 ::shows_by_alphabetical_order returns an array of all of the shows, listed in alphabetical order def self.highest_rating Show.maximum("rating") end def self.most_popular_show num = Show.highest_rating Show.where("rating = (?)", num)[0] end def self.lowest_rating Show.minimum("rating") end def self.least_popular_show num = Show.lowest_rating Show.where("rating = (?)", num)[0] end def self.ratings_sum Show.sum("rating") end def self.popular_shows Show.where("rating > 5") end def self.shows_by_alphabetical_order Show.order("name ASC") end !* More methods! def self.find_longest_username self.all end
true
651fe2ca6fdb38816069e13bfa9218c074276a7a
Ruby
RxMz/Book-List-Scraper
/app/workers/report_worker.rb
UTF-8
921
2.6875
3
[]
no_license
class ReportWorker include Sidekiq::Worker sidekiq_options rety: true def perform(book_lists) data = string_generator(book_lists) return data end def string_generator(book_lists) entries = "" book_lists.each { |book_list| book_list.courses.each { |course| department = course.department course_number = course.number course.books.each { |book| entries += sprintf("%-7s", department) entries += sprintf("%-6d", course_number) entries += sprintf("%-32s", "") # book edition entries += sprintf("%-14s", "") # ISBN entries += sprintf("%-9s", "") # ISBN INT entries += sprintf("%-24s", book.author) entries += sprintf("%-55s", book.title) entries += sprintf("%-5.2f", book.price) entries += sprintf("%-10s", book.publisher) } entries += "\n" #creating new line after every entry } } end end
true
f170ba13733838c91ec13d9b820d86b971c1e983
Ruby
DanM2010/ruby-challenges
/first_class_parent_child.rb
UTF-8
1,772
3.625
4
[]
no_license
class Match puts "Hello!" def set_date=(date) @date = date end def get_date return @date end def set_final_score=(final_score) @final_score = final_score end def get_final_score return @final_score end def set_home_team=(home_team) @home_team = home_team end def get_home_team return @home_team end def set_away_team=(away_team) @away_team = away_team end def get_away_team return @away_team end end class Goal < Match def set_scorer=(scorer_name) @name = scorer_name end def get_scorer return @name end def set_scored_for=(scored_for_team) @for_team = scored_for_team end def get_scored_for return @for_team end def set_assisted_by=(assisted_by) @assist = assisted_by end def get_assisted_by return @assist end def set_time_of_goal=(time_of_goal) @time = time_of_goal end def get_time_of_goal return @time end def set_current_score=(current_score) @current_score = current_score end def get_current_score return @current_score end end great_goal = Goal.new great_goal.set_scorer = "Troy Deeney" great_goal.set_home_team = "Watford" great_goal.set_away_team = "Leicester City" great_goal.set_scored_for = "Watford" great_goal.set_assisted_by = "Jonathan Hogg" great_goal.set_time_of_goal = "96:52" great_goal.set_current_score = "Wat 3-1 Lei" great_goal.set_final_score = "Wat 3-1 Lei" scorer = great_goal.get_scorer goal_for = great_goal.get_scored_for current_score = great_goal.get_current_score final_score = great_goal.get_final_score puts "#{scorer} scores for #{goal_for} to make it #{current_score}!!" puts "The whistle has gone and the final score is #{final_score}"
true
389eaa19492dc66d9ee2810ff8b711331b85a948
Ruby
gokuhadi/RubyTraining
/ruby_project/iter.rb
UTF-8
116
3.296875
3
[]
no_license
#ary = [1,2,3,4,5] #ary.each do |i| # puts i #end #has = { a:1,b:2, c:3, d:4, e:5} #has.each { |k,v| puts k }
true
58b8d6e29661e263065788dcdaef616422c2b13c
Ruby
mkhoeini/kelasiTline
/spec/models/post_spec.rb
UTF-8
1,762
2.65625
3
[]
no_license
require "spec_helper" describe Post do before do @post = Post.create do |p| p.msg = "test message" end end it "Should have a parent" do p = Post.new parent_id: @post.id p.parent.should be_an_instance_of Post end it "Should have replies" do Post.create {|q| q.msg = 'reply'; q.parent_id = @post.id } @post.replies.count.should == 1 end it "Should sort by 'created_at desc' by default" do p1 = Post.create {|q| q.msg = '1'} p2 = Post.create {|q| q.msg = '2'} Post.first(2).should == [p2, p1] end it "Should have recent posts" do ps = [] 30.times do |i| ps << Post.create {|q| q.msg = i.to_s} end Post.recent_posts(10).should == ps.last(10).reverse end it "Should have post.parent_id==nil as recent_posts" do p = Post.create {|q| q.parent_id = nil; q.msg = 'nil message'} Post.recent_posts.should include p end it "Should have a user" do p = Post.create user_id: 1 p.user.should == User.find(1) end it "Should refuse to save a post with empty message" do p = Post.new p.save expect(p.errors.messages).to have_key :msg expect(p.errors.messages[:msg]).to include "can't be blank" end context "HTML Pipeline" do describe :message= do subject { Post.new } it "should respond to message=" do expect(subject.respond_to? :message=).to be_true end it "should understand links" do subject.message = "http://example.com" expect(subject.msg).to eq '<p><a href="http://example.com">http://example.com</a></p>' end it "should understand markdown" do subject.message = "This _is_ **text**" expect(subject.msg).to eq '<p>This <em>is</em> <strong>text</strong></p>' end end end end
true
c38049ddd12d1efced7876ebf2c0a36fd4531dde
Ruby
rodovich/inactive-record
/inactive_record/relation.rb
UTF-8
1,729
2.625
3
[]
no_license
module InactiveRecord class Relation def initialize(klass, params = {}) @klass = klass @params = params @params[:where] ||= [] @params[:order] ||= [] @params[:limit] ||= nil end # return a new relation, including the new `where` conditions def where(conditions) Relation.new(@klass, @params.merge(where: @params[:where] + conditions.to_a)) end # return a new relation, including the new `order` criteria def order(*criteria) Relation.new(@klass, @params.merge(order: @params[:order] + criteria)) end # return a new relation, including the new `limit` number def limit(number) Relation.new(@klass, @params.merge(limit: number)) end def first @first ||= limit(1).to_a.first end def to_a @to_a ||= execute_select('*') .map { |attributes| @klass.new(attributes) } end def count @count ||= execute_select('count(*)') .first['count'].to_i end def map(&block) to_a.map(&block) end def inspect "[#{to_a.map(&:inspect).join(', ')}]" end private def execute_select(selection) clauses = [] clauses << "select #{selection}" clauses << "from #{table_name}" if @params[:where].any? clauses << "where #{@params[:where].map { |name, value| "#{name} = '#{value}'" }.join(' and ')}" end if @params[:order].any? clauses << "order by #{@params[:order].join(', ')}" end if @params[:limit] clauses << "limit #{@params[:limit]}" end InactiveRecord.execute_sql("#{clauses.join(' ')};") end def table_name @klass.name.underscore.pluralize end end end
true
7a247371cdaad241f5ef79baeaffac0d95b477b7
Ruby
mikowitz/rubypond
/test/sharp_test.rb
UTF-8
1,033
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require File.dirname(__FILE__) + "/test_helper" describe "Sharp" do before :each do @fs = Sharp.new(f) end it "#name should return the correct value" do @fs.name.should == "fs" end it "#offset should return the correct value" do @fs.offset.should == 6 end it "#natural_offest should return the correct value" do @fs.natural_offset.should == 5 end it "#accidental should return the correct value" do @fs.accidental.should == f end it "#sharp should return the correct value" do @fs.sharp.should == f.sharp.sharp end it "#flat should return the correct value" do @fs.flat.should == f end it "#natural should return the correct value" do @fs.natural.should == f end describe "validations" do [1, {1 => 2}, [1,2], "hello"].each do |accidental| it "should raise an ArgumentError if created with #{accidental.inspect} as an accidental" do lambda { Sharp.new(accidental) }.should raise_error ArgumentError end end end end
true
5977ebac5df301176b42a654043d2798fc1b0464
Ruby
curlywallst/ttt-with-ai-project-v-000
/lib/players/computer.rb
UTF-8
2,476
3.484375
3
[]
no_license
module Players class Computer < Player attr_accessor :move WIN_COMBINATIONS = [ [0,1,2], # Top row [3,4,5], # Middle row [6,7,8], # Bottom row [0,3,6], # Left column [1,4,7], # Middle column [2,5,8], # Right row [0,4,8], # First diagonal [2,4,6] # Second diagonal ] def move(board) @status = false @move_made="" empty_cells = empty_moves(board) number_of_moves_left = empty_cells.count if self.token == "X" other_player_token = "O" else other_player_token = "X" end if empty_cells.include?(4) #takes center block if it can @move_made = "5" else if @status == false check_winning_combinations(self.token, board) end #if end if @status == false check_winning_combinations(other_player_token, board) end #if end if @status == false check_winning_combinations(" ", board) end if @status == false #selects random if all else fails @move_made = empty_cells[rand(0..number_of_moves_left-1)]+1 @status = true @move_made.to_s end end #else end @move_made end #move end def check_winning_combinations(token_to_check, board) WIN_COMBINATIONS.each do |combination| if @status == false by_player_moves = Hash.new 0 combination.each do |combo| by_player_moves[board.cells[combo]] += 1 end # do end if by_player_moves[token_to_check] == 2 row = [] row = [board.cells[combination[0]],board.cells[combination[1]],board.cells[combination[2]]] if row.find_index(" ") if token_to_check == (" ") row_index = row.find_index(" ") if row_index != 1 || 3 || 7 || 9 #pick corner row[row_index] = "N" row.find_index(" ") end end @move_made = combination[row.find_index(" ")]+1 @status = true @move_made = @move_made.to_s end #if end end # if by_player end end # if status end end # do end end def empty_moves(board) array = [] index = 0 board.cells.each do |i| if i == " " array.push(index) end index+=1 end array end end end
true
042b31f7512bb12632e4f6f2103711b8aee9356f
Ruby
rarayukawa/pro_ruby
/4.7.13.rb
UTF-8
1,048
3.359375
3
[]
no_license
#要素が5つで'default'を初期値とする配列を作成する a = Array.new(5, 'default') a #=> ["default", "default", "default", "default", "default"] #1番目の要素を取得する str = a[0] str #=> "default" #1番目の要素を大文字に変換する(破壊的変更) str.upcase! str #=> "DEFAULT" #配列の要素全てが大文字に変わってしまう a #=>["DEFAULT", "DEFAULT", "DEFAULT", "DEFAULT", "DEFAULT"] #ブロックを使って、ブロックの戻り値を初期値とする a = Array.new(5) { 'default' } a #=> ["default", "default", "default", "default", "default"] #1番目の要素を取得する str = a[0] str #=> "default" #1番目の要素を大文字に変換する(破壊的変更) str.upcase! str #=> "DEFAULT" #1番目の要素だけが大文字になり、他は変わらない a #=>["DEFAULT", "default", "default", "default", "default"] #同じ値で同一のオブジェクト a = Array.new(5, 'default') #同じ値で異なるプロジェクト a = Array.new(5) { 'default' }
true
934ec4767de94c9bf0ebe9f958bce27bef128a08
Ruby
jrupinski/app-academy
/rails/music_app/app/helpers/tracks_helper.rb
UTF-8
248
2.53125
3
[]
no_license
module TracksHelper def ugly_lyrics(lyrics) note_sign = '&#9835;' formatted_lyrics = '' lyrics.each_line do |line| formatted_lyrics << "#{note_sign} #{h(line)}" end "<pre>#{formatted_lyrics}</pre>".html_safe end end
true
e5d885eb33f7fc9a1810b82fb0e8070c435a3d08
Ruby
dorianwolf/math_game
/methods.rb
UTF-8
1,341
4.0625
4
[]
no_license
def begin_game # INITIALIZE puts "How many players will there be?" num_players = gets.chomp.to_i @players = [] @loser = nil # CREATE PLAYERS num_players.times do |num| @player = { name: "", health: 3, score: 0 } puts "What is the name of player #{num+1}?" @player[:name] = gets.chomp @players << @player end play_game end def play_round(player) num_1 = rand(20) num_2 = rand(20) ans = num_1 + num_2 puts "#{player[:name]} is up! Here's your question:" puts "What is #{num_1} + #{num_2}?" answer = gets.chomp.to_i if answer == ans then player[:score] += 1 puts "RIGHT!" puts "" else player[:health] -= 1 puts "WRONG! current score is" puts "" @players.each {|plyr| puts "#{plyr[:name]}: #{plyr[:health]}"} puts "" end end def play_game while !@loser do @players.each do |player| play_round(player) if !@loser if player[:health] == 0 then @loser = player[:name] puts "Game over! #{player[:name]} loses pitifully." print "Once again, " ask_to_play end end end end def ask_to_play puts "would you like to play?" answer = gets.chomp.to_s.downcase case answer when "yes" begin_game when "no" puts "fine.." else puts "huh?" ask_to_play end end
true
52f17b1b1e32d1d0e00ea282cddd8ffab3716081
Ruby
karlwitek/launch_school_rb120
/lesson4/hard1_prob3ls.rb
UTF-8
3,213
3.953125
4
[]
no_license
# Problem 3: Incorporate a new Motorboat class (1 hull, 1 propeller) and behaves similar to Catarmaran. # Create a new class to present the common elements of motorboats and catamarans. (Seacraft). We still # want to include the Moveable module to get support for calculating the range. module Moveable attr_accessor :speed, :heading attr_writer :fuel_capacity, :fuel_efficiency def range @fuel_capacity * @fuel_efficiency end end class WheeledVehicle include Moveable def initialize(tire_array, km_traveled_per_liter, liters_of_fuel_capacity) @tires = tire_array self.fuel_efficiency = km_traveled_per_liter self.fuel_capacity = liters_of_fuel_capacity end def tire_pressure(tire_index) @tires[tire_index] end def inflate_tire(tire_index, pressure) @tires[tire_index] = pressure end end class Seacraft include Moveable attr_reader :hull_count, :propeller_count def initialize(num_propellers, num_hulls, fuel_efficiency, fuel_capacity) @propeller_count = num_propellers @hull_count = num_hulls self.fuel_efficiency = fuel_efficiency self.fuel_capacity = fuel_capacity end def range @fuel_capacity * @fuel_efficiency + 10 end end # We can now implement a Motorboat based on the Seacraft definition. We don't need to reference to Moveable # since that is already included in the Seacraft super class. class Motorboat < Seacraft def initialize(km_traveled_per_liter, liters_of_fuel_capacity) super(1, 1, km_traveled_per_liter, liters_of_fuel_capacity) end end class Catamaran < Seacraft # def initialize(num_propellers, num_hulls, km_traveled_per_liter, liters_of_fuel_capacity) # super # end // The super method automatically passes along any arguments which the original method received # because of this, we can remove the arguments being passed into super (above) # In fact, because super is the only statement in this initialize method and there's nothing to override it # we can remove it altogether end class Auto < WheeledVehicle def initialize # 4 tires are various tire pressures super([30,30,32,32], 50, 25.0) end end class Motorcycle < WheeledVehicle def initialize # 2 tires are various tire pressures super([20,20], 80, 8.0) end end boat = Motorboat.new(40, 13.5) puts boat.range# 540.0 puts boat.hull_count# 1 puts boat.propeller_count# 1 my_cat = Catamaran.new(4, 2, 35, 12.5) puts my_cat.range# 437.5 puts my_cat.hull_count# 2 bike = Motorcycle.new puts bike.tire_pressure(1)# 20 bike.inflate_tire(1, 35) puts bike.tire_pressure(1)# 35 # Problem 4: Make adjustment for how the range of vehicles is calculated. For the seaborne vehicles, add # an additional 10km of range even if the vehicle is out of fuel. Autos and Motorcycles will stay the same. boat = Motorboat.new(80, 8.0) puts boat.range# 650.0 bike = Motorcycle.new puts bike.range# 640.0 # good. created own range method in Seacraft. # LS: similar to my solution (override in Seacraft), but uses super to get the value first, then adds 10 # def range # super + 10 # end
true
cf7ec7237e881ec423fc88cc201fc0ee4ddcb5fa
Ruby
tscholz/artifactory-gem_import
/lib/artifactory/gem_import/worker/importer.rb
UTF-8
3,979
2.625
3
[]
no_license
require "tmpdir" require "fileutils" module Artifactory module GemImport module Worker class Importer < Base attr_reader :source_repo, :target_repo, :only def initialize(source_repo:, target_repo:, only: /.+/) @source_repo = source_repo @target_repo = target_repo @only = only end def import! output_counts missing_gems .map { |spec| Gem.new spec: spec, source_repo: source_repo, target_repo: target_repo, cache_dir: tmp_dir } .each { |gem| process gem } summary ensure remove_tmp_dir! end private def output_counts publisher.tell ["Source Repo (#{source_repo.url})", :count, GemSpecs.get(repo: source_repo, only: only).count] publisher.tell ["Target Repo (#{target_repo.url})", :count, GemSpecs.get(repo: target_repo, only: only).count] publisher.tell ["Missing in target repo", :count, missing_gems.count] end def process(gem) publisher.tell [gem, :processing] download(gem) and upload(gem) and verify(gem) cleanup(gem) if gem.errors.on(:verify).any? end def missing_gems @missing_gems ||= GemSpecs.missing_gems source_repo: source_repo, target_repo: target_repo, only: only end def download(gem) publisher.tell [gem, :downloading] status, msg = downloader.call gem.source_url, gem.cache_path if status == :ok bookkeeper.tell [gem, :downloaded, 1] else gem.errors.add :downlod, msg bookkeeper.tell [gem, :download_failed, 1] end publisher.tell [gem, :status, status] status == :ok end def upload(gem) publisher.tell [gem, :uploading] status, msg = uploader.call gem.target_url, gem.target_headers, gem.cache_path if status == :ok gem.foreign_representation = msg bookkeeper.tell [gem, :uploaded, 1] else gem.errors.add :upload, msg bookkeeper.tell [gem, :upload_failed, 1] end publisher.tell [gem, :status, status] status == :ok end def verify(gem) publisher.tell [gem, :verifying] status, msg = verifier.call gem.cache_path, gem.foreign_representation if status == :ok bookkeeper.tell [gem, :verified, 1] else gem.errors.add :verify, msg reviewer.tell gem bookkeeper.tell [gem, :verification_failed, 1] end publisher.tell [gem, :status, status] status == :ok end def cleanup(gem) publisher.tell [gem, :cleaning] status, msg = cleaner.call gem.target_url, gem.target_headers if status == :ok bookkeeper.tell [gem, :cleaned, 1] else gem.errors.add :cleanup, msg reviewer.tell gem bookkeeper.tell [gem, :cleanup_failed, 1] end publisher.tell [gem, :status, status] status == :ok end def downloader @downloader ||= Gems.downloader end def uploader @uploader ||= Gems.uploader end def verifier @verifier ||= Gems.verifier end def cleaner @cleaner ||= Gems.cleaner end def remove_tmp_dir! FileUtils.remove_entry tmp_dir end def tmp_dir @tmp_dir ||= Dir.mktmpdir end end end end end
true
941c302e1f1734b9d63a6c6f8bcd2d0d8ab17890
Ruby
mxenabled/firebolt
/lib/firebolt/file_warmer.rb
UTF-8
612
2.59375
3
[ "MIT" ]
permissive
require 'firebolt/warmer' module Firebolt class FileWarmer include ::Firebolt::Warmer def perform return nil unless cache_file_exists? parsed_contents end private def cache_file ::Firebolt.config.cache_file end def cache_file_exists? ::File.exists?(cache_file) end def file_contents ::File.open(cache_file) do |file| file.read end end def parsed_contents ::JSON.parse(file_contents) rescue => e warn "Could not parse #{cache_file}, falling back to default warmer." return nil end end end
true
51309fc34b73bc140e0b1dc55901cbc4545e5b4a
Ruby
wesleyhuang23/programming-lessons
/ruby/4. redacted.rb
UTF-8
364
4.09375
4
[]
no_license
#Redacted puts "please type a response" text = gets.chomp puts "the word you want to redact" redacted = gets.chomp #split method - splits a string and returns an array words = text.split(" ") #each is kind of like each, map create new array in JS words.each do |word| if word == redacted print "REDACTED" else print word + " " end end
true
0b8d0c78170b0be05dc4bca2daf906e0f9748f16
Ruby
Beondel/key-for-min-value-001-prework-web
/key_for_min.rb
UTF-8
296
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) low_key = nil name_hash.each_key { |key| low_key = key if low_key == nil || name_hash[key] < name_hash[low_key]} low_key end
true
2dc9d25fc86e612dc6e4fca3574d5c03a2da09c5
Ruby
lesniakania/social_network_analyser
/spec/social_network_analyser_spec.rb
UTF-8
3,997
2.65625
3
[]
no_license
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'social_network_analyser' require 'node' require 'edge' require 'graph' describe SocialNetworkAnalyser do before(:each) do @nodes = (0..4).map { |id| Node.new(id) } end describe "degree centrality" do it "should compute outdegree centrality properly" do src = Node.new(5) edges = [] @nodes.each { |n| edges << Edge.new(src, n) } @nodes << src graph = Graph.new(@nodes, edges) SocialNetworkAnalyser.outdegree_centrality(graph, src.id).should == 5 end it "should compute indegree centrality properly" do src = Node.new(5) edges = [] @nodes.each { |n| edges << Edge.new(n, src) } @nodes << src graph = Graph.new(@nodes, edges) SocialNetworkAnalyser.indegree_centrality(graph, src.id).should == 5 end end describe "page rank" do it "should compute page rank properly" do edges = [] edges << Edge.new(@nodes[0], @nodes[1]) edges << Edge.new(@nodes[0], @nodes[2]) edges << Edge.new(@nodes[1], @nodes[3]) edges << Edge.new(@nodes[1], @nodes[4]) edges << Edge.new(@nodes[2], @nodes[3]) edges << Edge.new(@nodes[2], @nodes[4]) edges << Edge.new(@nodes[3], @nodes[4]) graph = Graph.new(@nodes, edges) SocialNetworkAnalyser.page_rank(graph, @nodes[4].id).should == 0.613621875 end end describe "betweenness centrality" do it "should compute betweenness centrality properly" do (5..6).each { |id| @nodes << Node.new(id) } edges = [] edges << Edge.new(@nodes[0], @nodes[1]) edges << Edge.new(@nodes[1], @nodes[2]) edges << Edge.new(@nodes[2], @nodes[3]) edges << Edge.new(@nodes[0], @nodes[4]) edges << Edge.new(@nodes[1], @nodes[5]) edges << Edge.new(@nodes[4], @nodes[5]) edges << Edge.new(@nodes[5], @nodes[6]) graph = Graph.new(@nodes, edges) betweenness = SocialNetworkAnalyser.betweenness_centrality(graph) betweenness[@nodes[1].id].should == 3 betweenness[@nodes[4].id].should == 1 nodes = (0..2).map { |id| Node.new(id) } edges = [] edges << Edge.new(nodes[1], nodes[0]) edges << Edge.new(nodes[0], nodes[2]) graph = Graph.new(nodes, edges) betweenness = SocialNetworkAnalyser.betweenness_centrality(graph) betweenness[nodes[0].id].should == 1 end end describe "centrality based on dijkstra alghoritm" do before(:each) do @edges = [] @edges << Edge.new(@nodes[0], @nodes[1]) @edges << Edge.new(@nodes[0], @nodes[2]) @edges << Edge.new(@nodes[2], @nodes[3]) @edges << Edge.new(@nodes[3], @nodes[4]) @graph = Graph.new(@nodes, @edges) end describe "closeness centrality" do it "should compute closeness centrality properly" do SocialNetworkAnalyser.closeness_centrality(@graph, @nodes[0].id).should == 1.0/7 end end describe "graph centrality" do it "should compute graph centrality properly" do SocialNetworkAnalyser.graph_centrality(@graph, @nodes[0].id).should == 1.0/3 end end end describe "detect communities" do it "should detect communities properly" do nodes = (0..5).map { |id| Node.new(id) } edges = [] edges << Edge.new(nodes[0], nodes[1]) edges << Edge.new(nodes[1], nodes[0]) edges << Edge.new(nodes[0], nodes[2]) edges << Edge.new(nodes[2], nodes[0]) edges << Edge.new(nodes[1], nodes[4]) edges << Edge.new(nodes[4], nodes[1]) edges << Edge.new(nodes[4], nodes[3]) edges << Edge.new(nodes[3], nodes[4]) edges << Edge.new(nodes[4], nodes[5]) edges << Edge.new(nodes[5], nodes[4]) graph = Graph.new(nodes, edges) community = SocialNetworkAnalyser.detect_communities!(graph, :weak_community) community.subgraphs.map { |s| s.nodes.keys }.should == [[5, 3, 4], [0, 1, 2]] end end end
true
852e50d70f093df3c3f44b940caa7a2b6636848d
Ruby
tkengo/meta_graph
/lib/meta_graph/collection.rb
UTF-8
741
3.109375
3
[]
no_license
module MetaGraph # # *Collection* class presents an array data in Facebook Graph API. # class Collection include GraphAccessor include Enumerable # # Create *Collection* instance from an array. # # === Arguments # [access_token] access token to read a data from Graph API. # Please set to oauth's access_token. # [collection] An array of collection data. # def initialize(access_token, collection) @access_token = access_token @collection = collection end def [](index) read_graph(@access_token, @collection[index]) end def each @collection.each_with_index do |value, index| yield self[index] end end end end
true
42efbf318d61af42161e77f9d03ede2152f1d8a9
Ruby
xuhui-github/rubydailyprogramming
/class/abstractgreeter.rb
UTF-8
318
3.078125
3
[]
no_license
class AbstractGreeter def greet puts "#{greeting} #{who}" end end class WorldGreeter <AbstractGreeter def greeting;"hello";end def who;"world";end end class SpanishGreeter <AbstractGreeter def greeting;"hola";end def who;"world";end end WorldGreeter.new.greet SpanishGreeter.new.greet
true
72b4b6dba26a9a050bc45f4a729a2461d8ebc91d
Ruby
AuthorizeNet/sample-code-ruby
/PaymentTransactions/charge-tokenized-credit-card.rb
UTF-8
2,768
2.546875
3
[ "MIT" ]
permissive
require 'rubygems' require 'yaml' require 'authorizenet' require 'securerandom' include AuthorizeNet::API def charge_tokenized_credit_card() config = YAML.load_file(File.dirname(__FILE__) + "/../credentials.yml") transaction = Transaction.new(config['api_login_id'], config['api_transaction_key'], :gateway => :sandbox) request = CreateTransactionRequest.new request.transactionRequest = TransactionRequestType.new() request.transactionRequest.transactionType = TransactionTypeEnum::AuthCaptureTransaction request.transactionRequest.amount = ((SecureRandom.random_number + 1 ) * 150 ).round(2) request.transactionRequest.payment = PaymentType.new request.transactionRequest.payment.creditCard = CreditCardType.new('4242424242424242','0728','123',nil,"EjRWeJASNFZ4kBI0VniQEjRWeJA=") request.transactionRequest.order = OrderType.new("invoiceNumber#{(SecureRandom.random_number*1000000).round(0)}","Order Description") response = transaction.create_transaction(request) if response != nil if response.messages.resultCode == MessageTypeEnum::Ok if response.transactionResponse != nil && response.transactionResponse.messages != nil puts "Successfully charged tokenized credit card (authorization code: #{response.transactionResponse.authCode})" puts "Transaction Response code: #{response.transactionResponse.responseCode}" puts "Code: #{response.transactionResponse.messages.messages[0].code}" puts "Description: #{response.transactionResponse.messages.messages[0].description}" else puts "Transaction Failed" if response.transactionResponse.errors != nil puts "Error Code: #{response.transactionResponse.errors.errors[0].errorCode}" puts "Error Message: #{response.transactionResponse.errors.errors[0].errorText}" end raise "Failed to charge tokenized credit card." end else puts "Transaction Failed" if response.transactionResponse != nil && response.transactionResponse.errors != nil puts "Error Code: #{response.transactionResponse.errors.errors[0].errorCode}" puts "Error Message: #{response.transactionResponse.errors.errors[0].errorText}" else puts "Error Code: #{response.messages.messages[0].code}" puts "Error Message: #{response.messages.messages[0].text}" end raise "Failed to charge tokenized credit card." end else puts "Response is null" raise "Failed to charge tokenized credit card." end return response end if __FILE__ == $0 charge_tokenized_credit_card() end
true
aa0e034e46bf117f8818e725b35b651410c25ea5
Ruby
chrbradley/population
/lib/analytics.rb
UTF-8
7,222
3.765625
4
[]
no_license
class Analytics attr_accessor :options, :m_id def initialize(areas) @areas = areas # => set @areas class variable to areas argument passed to Analytics.new set_options end def set_options @options = [] # => create an instance variable to hold a menu # => menu will be an array of hashes. Each hash has 3 keys: menu_id, menu_title, method # => menu_id is the number that shows up in the menu # => menu_title is the text displayed in the menu # => method is the method called is it's option is picked by the user @options << { menu_id: 6, menu_title: 'Ballers', method: :ballers} @options << { menu_id: 7, menu_title: 'Puapers', method: :paupers} @options << { menu_id: 8, menu_title: 'Palindromes', method: :palindrome} @options << { menu_id: 9, menu_title: 'Mattingly', method: :mattingly} @options << { menu_id: 1, menu_title: 'Areas Count', method: :how_many } @options << { menu_id: 2, menu_title: 'Smallest Population (non 0)', method: :smallest_pop } @options << { menu_id: 3, menu_title: 'Largest Population', method: :largest_pop } @options << { menu_id: 4, menu_title: 'How many zip codes in California?', method: :california_zips } @options << { menu_id: 5, menu_title: 'Information for a given zip code:', method: :zip_info } @options << { menu_id: 10, menu_title: 'Exit', method: :exit } end def run(choice) opt = @options.select {|o| o[:m_id] == choice }.first if opt.nil? # => validates choice puts "Invalid Choice" # => Puts error message if user select invalid option elsif opt[:method] != :exit # => Exits if user select exit self.send opt[:method] :done else opt[:method] # => runs method associated with valid choice end end # => Menu Item Methods def how_many puts "There are #{@areas.length} areas." # => Prints a string with the number of areas end def smallest_pop # => Returns the city and state with the smallest population sorted = @areas.sort do |x,y| x.estimated_population <=> y.estimated_population # => compares areas based on population size end smallest = sorted.drop_while { |i| i.estimated_population == 0}.first # => Sorts smallest to largest. Drops areas with 0 population puts "#{smallest.city}, #{smallest.state} has the smallest population of #{smallest.estimated_population}." end def largest_pop # => Returns city and state with the largest population sorted = @areas.sort do |x,y| x.estimated_population <=> y.estimated_population # => compares areas based on population size end largest = sorted.reverse.drop_while { |i| i.estimated_population == 0 }.first # => Sorts largest to smallest. Drops areas with 0 population puts "#{largest.city}, #{largest.state} has the largest population of #{largest.estimated_population}." end def california_zips # => returns the number of population codes in California c = @areas.count { |a| a.state == "CA"} puts "There are #{c} zip code matches in California." end def zip_info # => takes a population code (zip code) as an argument and retuns all available information about it. print "Enter zip code: " zip = gets.strip.to_i zips = @areas.select { |a| a.zipcode == zip } unless zips.empty? puts "" zips.each { |z| puts z} else puts "Zip code not found." end end def ballers # => Returns city with highest total wages sorted = @areas.sort do |x,y| x.total_wages <=> y.total_wages # => compares areas based on wages end # largest = sorted.reverse.drop_while { |i| i.total_wages == 0}.first # => sorts largest to smallest. Drops areas with ) total wages # puts "All the ballers, averaging #{largest.total_wages} dollars per year, ball in #{largest.city}, #{largest.state}." largest_10 = sorted.reverse.drop_while { |i| i.total_wages == 0}.uniq { |s| s.zipcode }.take(10) # => sorts largest to smallest. Drops areas with ) total wages puts "The 10 best places to live if your're a Baller are:" # largest_10.each {|x| puts "Averaging #{x.total_wages} dollars per year, #{x.city}, #{x.state}."} largest_10.each {|x| puts "#{x.city}, #{x.state} in zip code #{x.zipcode}. The average income is #{x.total_wages} dollars per year," } end def paupers # => Returns city with lowest total wages sorted = @areas.sort do |x,y| x.total_wages <=> y.total_wages # => compares areas based on wages end lowest = sorted.drop_while { |i| i.total_wages ==0 }.uniq { |s| s.zipcode }.take(10) # Sorts smallest to largest, droppng areas with 0 total wages puts "The 10 places you're least likely to run into a Baller are:" lowest.each { |x| puts "#{x.city}, #{x.state} in zip code #{x.zipcode}. The average income is #{x.total_wages} dollars per year," } end def palindrome # => Returns all palindrome zip codes sorted = @areas.sort do |x,y| x.zipcode <=> y.zipcode # => sorts based on zipcodes end strings =[] # => initialie palindromes = [] # => initialize sorted.each { |x| strings << x.zipcode.to_s} # => returns array of zipcode strings strings.each do |item| # => compares each zip with it's reverse if item == item.reverse palindromes << item # => if they match, add to palindrome array end end palindromes.uniq! # => eliminate duplicates puts "There are #{palindromes.size} palindrome zip codes. Here they are:" palindromes.each { |item| puts "#{item}"} end def mattingly # => returns all zip codes whose digits add upto 23 sorted = @areas.sort do |x,y| x.zipcode <=> y.zipcode # => sorts based on zipcodes end strings = [] sorted.reverse.each { |x| strings << x.zipcode.to_s} # => returns array of zipcode strings # sorted.reverse.take(10000).each { |x| strings << x.zipcode.to_s} # puts "strings size is #{strings.size}" strings.uniq! # => eliminates duplicates # puts "strings unique size is #{strings.size}" # integers.each { |x| puts "#{x}"} array_of_digits = [] # => initialize array to hold string/digit hashes digits_hash = {} # => initialize string/digit hash strings.each { |x| array_of_digits << {x => x.chars.map(&:to_i)}} # => takes each item from strings arrya, gets digit version, adds to string digit array # strings.each { |x| array_of_digits << x.chars.map(&:to_i)} # puts "array_of_digits size is #{array_of_digits.size}" # array_of_digits.each { |x| puts "#{x}" } donny_baseball = [] # => initialize array to hold valid results array_of_digits.each do |item| # => iterate over each string/digit pair item.each do |key, value| # => iterate over each digit index = 0 total = 0 while value[index] total += value[index] # => adds digits index += 1 # => increments end # puts "the total is #{total}" if total == 23 # => condition donny_baseball << key # => if satisfied add to array end end end puts "There are #{donny_baseball.size} Mattingly zip codes:" puts donny_baseball # donny_baseball.each { |x| puts "#{x}" } end end
true
ff0e6b09f61d0ea239b5e02bf1deb4aa9cdb931a
Ruby
yuqiqian/ruby-leetcode
/94_BT_inorder_traversal.rb
UTF-8
318
3.1875
3
[]
no_license
def inorder_traversal(root) if root == nil return [] end stack = [root] current = root.left result = [] while stack.length != 0 || current!= nil while current!= nil stack << current current = current.left end current = stack.pop result << current.val current = current.right end result end
true
7facce8463cdd04c3b01e4ea7051ba431cb2c06d
Ruby
CedricBm/bergamotte-rails-coding-test
/test/models/item_test.rb
UTF-8
729
2.59375
3
[]
no_license
require 'test_helper' class ItemTest < ActiveSupport::TestCase test "sums the amount of item ordered" do paper = items(:paper) leather = items(:leather) assert_equal 5, paper.items_amount assert_equal 0, leather.items_amount end test "items has been ordered within the week timeframe" do items = Item.ordered_within_week(1.week.ago) paper = items(:paper) leather = items(:leather) assert items.include?(paper) assert items.exclude?(leather) end test "items has been ordered within the last week" do items = Item.ordered_within_week(nil) paper = items(:paper) leather = items(:leather) assert items.include?(paper) assert items.exclude?(leather) end end
true
f524c9983caf95cc951818bbf28bd558a3583609
Ruby
thejennywang/lockers
/spec/concierge_spec.rb
UTF-8
2,208
2.953125
3
[]
no_license
require 'concierge' require 'bag' require 'locker' describe 'Concierge' do let (:concierge) { Concierge.new } let (:small_bag) { double :small_bag, size: "small" } let (:medium_bag) { double :small_bag, size: "medium" } let (:large_bag) { double :small_bag, size: "large" } let (:all_available_lockers) { concierge.lockers.select{ |locker| !locker.full? && locker.acceptable?(small_bag) } } let (:medium_lockers) { concierge.lockers.select{ |locker| locker.size == "medium" } } let (:medium_and_large_lockers) { concierge.lockers.select{ |locker| !(locker.size == "small") } } it 'starts with all lockers available' do expect(all_available_lockers.length).to eq concierge.lockers.length end context 'when checking in a bag' do it 'can check in a bag' do concierge.check_in(small_bag) expect(concierge.lockers.first.bag).to eq small_bag end it 'can check in a medium bag into a large locker when medium lockers are full' do (medium_lockers.length).times {concierge.check_in(medium_bag)} concierge.check_in(medium_bag) first_large_locker = concierge.lockers.bsearch {|locker| locker.size == "large"} expect(first_large_locker.bag).to eq medium_bag end it 'knows when there are no more lockers available' do (all_available_lockers.length).times {concierge.check_in(small_bag)} expect{concierge.check_in(small_bag)}.to raise_error("Uh oh, no more lockers. Sorry.") end end context 'when checking out a bag' do it 'can check out a bag with a valid ticket_number' do concierge.check_in(small_bag) ticket_number = concierge.lockers.first.ticket_number expect(concierge.lockers.first).to be_full expect(concierge.lockers.first.bag).to eq small_bag concierge.check_out(ticket_number) expect(concierge.lockers.first).not_to be_full expect(concierge.lockers.first.bag).to eq nil end it 'cannot check out a bag with an invalid ticket_number' do invalid_ticket_number = 00 expect{concierge.check_out(invalid_ticket_number)}.to raise_error("Your ticket number is invalid.") end end end
true
1eec4c3ed62083eb4f122cf043ea0af175c68a95
Ruby
deild/RubyOnRailsEtudeDeCas
/e1/views/app/models/picture.rb
UTF-8
696
2.578125
3
[ "MIT", "Apache-2.0" ]
permissive
#--- # Excerpted from "Ruby on Rails, 2nd Ed." # We make no guarantees that this code is fit for any purpose. # Visit http://www.editions-eyrolles.com/Livre/9782212120790/ for more book information. #--- class Picture < ActiveRecord::Base validates_format_of :content_type, :with => /^image/, :message => "--- you can only upload pictures" def uploaded_picture=(picture_field) self.name = base_part_of(picture_field.original_filename) self.content_type = picture_field.content_type.chomp self.data = picture_field.read end def base_part_of(file_name) File.basename(file_name).gsub(/[^\w._-]/, '') end end
true
9c36cbf221a6d3d168c14595b812536b3be5412a
Ruby
DEFRA/waste-carriers-back-office
/app/services/reports/defra_quarterly_stats_service.rb
UTF-8
4,740
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "OGL-UK-3.0" ]
permissive
# frozen_string_literal: true # This is a minimalist implementation to meet an urgent requirement. It is expected to be enhanced later. module Reports class DefraQuarterlyStatsService < ::WasteCarriersEngine::BaseService attr_reader :start_date, :end_date, :abandon_rate, :abandon_rate_percent # rubocop:disable Layout/LineLength def run report = [] report << "Abandon rate is not directly tracked. Estimation:" activated_last_30_days = WasteCarriersEngine::Registration .where("metaData.dateActivated": { "$gte" => 30.days.ago }).count report << " - Registrations activated in the last 30 days: #{activated_last_30_days}" transients_last_30_days = WasteCarriersEngine::TransientRegistration .where(created_at: { "$gte" => 30.days.ago }).count report << " - Transient registrations remaining (registrations not completed) from the last 30 days: " \ "#{transients_last_30_days}" total_attempts_last_30_days = transients_last_30_days + activated_last_30_days report << " - Total registration attempts for the last 30 days: #{total_attempts_last_30_days}" @abandon_rate = total_attempts_last_30_days.zero? ? 0 : transients_last_30_days.to_f / total_attempts_last_30_days @abandon_rate_percent = (abandon_rate * 100.0).to_i report << " - Estimated abandon rate: #{@abandon_rate.round(3)} (#{@abandon_rate_percent}%)" report << "------------------------------------------------------------------------------------------------------------------" 4.downto(1).each do |q| report.concat(quarter_report(q)) report << "==================================================================================================================" end report end def quarter_report(quarters_ago) @start_date, @end_date = quarter_dates(quarters_ago) report = [] report << "Quarterly summary statistics for #{start_date} - #{end_date}" # summary statistics activated_total = count_activations activated_assisted_digital = count_activations("ASSISTED_DIGITAL") completed_online = activated_total - activated_assisted_digital report << "1. Number of orders completed online only, EXCLUDING Assisted Digital : " \ "#{activated_total} - #{activated_assisted_digital} = #{completed_online}" report << "2. Number of orders started and NOT completed: Unknown. Rough estimate based on abandon rate for the last 30 days:" report << " - Given #{completed_online} completed online with an abandon rate of #{@abandon_rate_percent}%:" report << " - ESTIMATED orders started online and not completed: " \ "#{estimate_started_online(completed_online, abandon_rate)}" report << "3. Same data as 1" report << "4. Total number of orders completed online AND via the Back office: #{activated_total} (of which AD: " \ "#{activated_assisted_digital})" report end # rubocop:enable Layout/LineLength private def count_activations(route = nil) match_clause = { "metaData.dateActivated": { "$gte" => start_date.midnight, "$lt" => (end_date + 1.day).midnight } } route.present? && match_clause["metaData.route"] = route result = WasteCarriersEngine::Registration.collection.aggregate( [ { "$match": match_clause }, { "$project": { order: "$financeDetails.orders" } }, { "$unwind": "$order" }, { "$group": { _id: 0, order_count: { "$sum": 1 } } } ] ).first result.present? ? result["order_count"] : 0 end def estimate_started_online(completed_online, abandon_rate) return "N/A" unless completed_online.positive? && abandon_rate < 1.0 "#{completed_online} / (1 - #{(@abandon_rate * 100.0).to_i}%) = " \ "#{(completed_online / (1 - @abandon_rate)).round(0)}" end def quarter_start_month(date) day_hash = (date.month * 100) + date.mday case day_hash when 401..630 4 when 631..930 7 when 1001..1231 10 when 101..331 1 else 0 end end # Zero quarters ago is the current quarter def quarter_dates(quarters_ago) today = Time.zone.today current_quarter_start = Date.new(today.year, quarter_start_month(today), 1) required_quarter_start = current_quarter_start - (3 * quarters_ago).months required_quarter_end = required_quarter_start + 3.months - 1.day [required_quarter_start, required_quarter_end] end end end
true
dfe77aee8278a7d204d6ee5fef89ba466394ec6e
Ruby
MisterMur/globetrottr
/app/models/activity.rb
UTF-8
1,533
2.59375
3
[ "MIT" ]
permissive
class Activity < ApplicationRecord belongs_to :destination has_many :trip_activities has_many :trips, through: :trip_activities # before_action :connect_google_api GOOGLE_API_KEY= ENV['GOOGLE_API_KEY'] def location #check trip association --> there's no relationship yet self.destination.to_s end def self.get_photo_url(spot) # byebug #maxwidth in url changes photo size if spot.photos.first == nil "Photo Unavailable" else ref = spot.photos.first.photo_reference "https://maps.googleapis.com/maps/api/place/photo?maxwidth=200&photoreference=#{ref}&key=#{GOOGLE_API_KEY}" end end def self.get_spots(type, id) location = Destination.find_by(id: id).to_s @client = GooglePlaces::Client.new( "#{GOOGLE_API_KEY}" ) @client.spots_by_query("#{type} near #{location}") end def self.create_by_api_connection(array, id, search) array.each do |spot| if self.find_by(name: spot.name) == nil self.create(name: spot.name, address: spot.formatted_address, rating: spot.rating, price_level: spot.price_level, photo_url: self.get_photo_url(spot), destination_id: id, search: search) else self.find_by(name: spot.name) end end end def self.select_by_search_and_destination(search, id) Activity.all.select do |activity| activity.search == search && activity.destination_id == id.to_i end end def format_address_for_search self.address.split(" ").join("%20") end end #end of Activity class
true
b49bca01cec406549d37a1254fb109174d4aaafc
Ruby
marcwright/WDI_ATL_1_Instructors
/REPO - DC - Students/w02/d03/Brett/gladiator/spec/arena_spec.rb
UTF-8
1,819
3.1875
3
[]
no_license
require_relative '../lib/arena' describe Arena do let (:arena) { Arena.new("colosseum") } describe "::new" do it "sets the arena's name and capitalizes" do expect( arena.name ).to eq "Colosseum" end end describe "#add_gladiator!" do it "adds a gladiator to the arena" do arena.add_gladiator!("Vorenus", "sword") expect( arena.gladiators.last.name ).to eq "Vorenus" end it "there can only be two gladiators in the arena at a time" do arena.add_gladiator!("Vorenus", "sword") arena.add_gladiator!("Pullo", "axe") arena.add_gladiator!("Maximus", "fists") expect( arena.gladiators.length ).to eq(2) end end describe "#fight!" do context "If there are two gladiators in the arena, you can call a fight method that results in the elimination of one of the gladiators from the arena." do it "need two gladiators" do arena.add_gladiator!("Vorenus", "sword") arena.add_gladiator!("Pullo", "axe") arena.fight! expect( arena.gladiators.length ).to eq(1) end it "Trident beats Spear" do arena.add_gladiator!("Vorenus", "trident") arena.add_gladiator!("Pullo", "spear") arena.fight! end it "Spear beats Club" do arena.add_gladiator!("Vorenus", "spear") arena.add_gladiator!("Pullo", "club") arena.fight! end it "Club beats Trident" do arena.add_gladiator!("Vorenus", "club") arena.add_gladiator!("Pullo", "trident") arena.fight! end it "if same weapon, both gladiators are elinminated" do arena.add_gladiator!("Vorenus", "trident") arena.add_gladiator!("Pullo", "trident") arena.fight! expect(@gladiators.length).to eq(0) end end end end
true
543f9ac21e8423791acd7d13b556a98c5c3b1ecc
Ruby
lcarrasco/CFDI
/lib/concepto.rb
UTF-8
1,539
3.0625
3
[ "WTFPL" ]
permissive
module CFDI # Un concepto del comprobante class Concepto < ElementoComprobante # @private @cadenaOriginal = [:cantidad, :unidad, :noIdentificacion, :descripcion, :valorUnitario, :importe] # @private attr_accessor *@cadenaOriginal # @private def cadena_original return [ @cantidad.to_i, @unidad, @noIdentificacion, @descripcion, self.valorUnitario, self.importe ] end # Asigna la descripción de un concepto # @param descricion [String] La descripción del concepto # # @return [String] La descripción como string sin espacios extraños def descripcion= descripcion @descripcion = descripcion.squish @descripcion end # Asigna el valor unitario de este concepto # @param dineros [String, Float, #to_f] Cualquier cosa que responda a #to_f # # @return [Float] El valor unitario como Float def valorUnitario= dineros @valorUnitario = dineros.to_f @valorUnitario end # El importe de este concepto # # @return [Float] El valor unitario multiplicado por la cantidad def importe return @valorUnitario*@cantidad end # Asigna la cantidad de (tipo) de este concepto # @param qty [Integer, String, #to_i] La cantidad, que ahuevo queremos en int, porque no, no podemos vender 1.5 Kilos de verga... # # @return [Integer] La cantidad def cantidad= qty @cantidad = qty.to_i @cantidad end end end
true
fb185371f6a0d5d05a290cdc904fa0b7f687cd13
Ruby
EMDevelop/battle
/lib/game.rb
UTF-8
237
3.40625
3
[]
no_license
class Game def initialize(player_one, player_two) @players = [player_one, player_two] end def player_one @players[0] end def player_two @players[1] end def attack(player) player.receive_damage end end
true
ed0223def905b86cec5a84ed40456a0adeeb38fb
Ruby
dasolari/platanus-challenge
/lib/views/game_view.rb
UTF-8
3,190
3.484375
3
[]
no_license
# frozen_string_literal: true require 'terminal-table' require_relative '../inputs' require_relative '../helpers/colorizer' # Singleton class in charge of the user interface and console prints class View @instance = new private_class_method :new class << self attr_reader :instance end def print_greeting display('Hello and welcome to this pokemon tournament', 2, true) end def print_players_and_stats(pokemons) players_table = Terminal::Table.new do |table| pokemons.each do |pokemon| pk = pokemon table << [pk.name, pk.hp, pk.attack, pk.defense, pk.special_attack, pk.special_defense, pk.speed] end center_table_columns(table) end players_table.headings = [' ', 'HP', 'Attack', 'Defense', 'Special Attack', 'Special Defense', 'Speed'] players_table.style = { all_separators: true } display_table(players_table) end def display_table(table) display('These are the Pokemons remaining in the tournament:', 2, false) puts table display('We advance to the next stage...', 1, true) end def center_table_columns(table) (1..6).each do |col| table.align_column(col, :center) end end def print_match_started(match_number, player1, player2) display("It's match number #{match_number} and we have #{player1} against #{player2}", 1.5, true, 1) end def print_attack(attacker, defender, attack_type, damage, type = nil) if type.nil? display("💥 #{attacker} does a #{attack_type} attack to #{defender} for #{damage} damage!", 0.4, false, 2, 'RED') elsif damage.zero? display("❌ #{attacker} does a SPECIAL attack, but #{defender} completely blocks it!!", 0.4, false, 2, 'RED') else display("💥 #{attacker} does a #{type} #{attack_type} attack to #{defender} for #{damage} damage!", 0.4, false, 2, 'RED') end end def print_effective_defense(defender) display("💪 #{defender} completely blocks off the attack!", 0.4, false, 2, 'BLUE') end def print_defense(defender, incoming_damage, actual_damage, hp_left) hit_msg = "💪 #{defender} takes a hit for #{incoming_damage}." damage_taken_msg = " Given it's defense and type, recieves #{actual_damage} damage. It is left with #{hp_left} HP!" display(hit_msg + damage_taken_msg, 0.4, false, 2, 'BLUE') end def print_defeated(defender) display("😵 #{defender} is defeated.", 1.4, true, 1, 'CYAN') end def print_match_winner(match_number, winner) display("Match number #{match_number} is finished and #{winner} is the winner!!", 2.5, true, 2, 'GREEN') end def print_deadlock_formed(attacker, defender) display("🔒 Deadlock formed. Reducing #{attacker} and #{defender}'s defense by 40%.", 0.6, false, 2, 'RED') end def print_tournament_winner(winner) display("👑 👑 #{winner} wins the tournament with a crushing victory 👑 👑", 3, true, 0, 'YELLOW') end def print_goodbye display('Goodbye :)', 0, false) end def display(text, sleep_time, line_skip, tab = 0, color = 'WHITE') puts ' ' * tab + COLOR[color].call(text) line_skip && puts sleep(sleep_time * GAME_SPEED) end end
true
f65b78ee393c3c0b7064a9c06aabb3753a15ca1f
Ruby
pokutuna/btproject
/spec/log_parser_spec.rb
UTF-8
2,361
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- require 'spec_helper' require 'log_parser' describe Record, 'when parsing log data' do before(:all) do @sample1 = '2009/11/10 10:39:12 pokutuna-ThinkPad 00:19:7E:F6:F5:5D' @sample2 = '2009/11/20 17:8:0 00:22:F3:9C:37:D8' @sample3 = '2009/11/20 17:10:0 hoge-pc 00:1B:DC:00:04:18' @sample4 = '2009/11/20 17:8:0 00:1B:DC:00:0F:5B' end it 'should parse a log line' do record = Record.new(@sample1) record.date.should == Time.local(2009,11,10,10,39,12) record.name.should == 'pokutuna-ThinkPad' record.bda.should == '00:19:7E:F6:F5:5D' end it 'should parse a log line without device name' do record = Record.new(@sample2) record.name.should == '' record.bda.should == '00:22:F3:9C:37:D8' end it 'should parse string has extra TAB between day and time' do record = Record.new(@sample3) record.name.should == 'hoge-pc' record.bda.should == '00:1B:DC:00:04:18' end it 'should mazide iketerunoka?' it 'should parse string has extra TAB without device name' do record = Record.new(@sample4) record.name.should == '' record.bda.should == '00:1B:DC:00:0F:5B' end end describe Record, 'when comparing' do before(:all) do @sample1 = Record.new('2009/11/8 19:13:8 pokutuna-ThinkPad 00:19:7E:F6:F5:5D') @sample2 = Record.new('2009/11/8 19:13:8 hoge 00:19:7E:F6:F5:5D') @sample3 = Record.new('2009/11/8 19:34:39 pokutuna-ThinkPad 00:19:7E:F6:F5:5D') end it 'should compare about same time Record object' do @sample1.should == @sample2 end it 'should compare about old time Record object' do @sample1.should < @sample3 end it 'should compare with Time object' do @sample1.should == Time.parse('2009/11/8 19:13:8') @sample1.should < Time.parse('2010/11/18 19:13:8') end end describe Logger do context 'when create new Logger object' do it 'should be empty Hashes' it 'should be zero, count default' it 'should be Unix epoch time, last contact default' end context 'when add_record' do it 'should raise ArgumentError by adding other class' it 'should raise RuntimeError by adding older record' end context 'when count by BDA' do it 'should return zero, unregistered BDA' end context 'when set/geting Threshold' do it 'should change by method' end end
true
bc9e0ba98ae41aaa4018ef2486aa1d328c0bb6ac
Ruby
SwtCharlie/Quick-Testing
/hlrb/killing.rb
UTF-8
192
2.640625
3
[]
no_license
homicide = Thread.new do while (1 == 1) puts "Don't kill me!" Thread.pass end end suicide = Thread.new do puts "This is all meaningless!" Thread.exit end Thread.kill(homicide)
true
f7af7a9cdda523171369b0d210c0225426c32dc2
Ruby
panickat/CodeaCampRuby
/sem4/dia1/2_publicovs_privado.rb
UTF-8
4,142
4.09375
4
[]
no_license
=begin Público Vs Privado El concepto de público y privado es muy importante dentro de un programa diseñado bajo el paradigma de OOP. Un objeto se compone de información y de métodos. Depende de como diseñes el objeto, si estos son públicos o privados. Es importante que un objeto solamente exponga lo indispensable y no toda la información que contiene. Simplemente debe compartir aquella información que otros objetos requieren para poder interactuar con ella. Este ejercicio te ayudará a comprender como es que un objeto hace pública o privada ya sea información o métodos. Objetivos Académicos Comprender la diferencia entre métodos privados y públicos Saber distinguir que hacer público de un objeto Actividades Deberás crear una clase Employee con las siguientes variables de instancia: name email salary deposit_account ¿Cuales de estas variables deben de tener un reader o writer? Piensa cual de estas variables deberán poder ser leídas o sobrescritas desde fuera de tu programa. Vamos a esconder algo de información. Deberás re-definir el método to_s para que regrese algo como esto: puts employee => Juan Perez <email: [email protected]> acct: 123456512 En el ejemplo anterior no es muy adecuando estar mostrando la cuenta de depósito del empleado. Crea un método privado que solamente muestre los últimos cuatro dígitos de este número. puts employee => Juan Perez <email: [email protected]> acct: *****6512 El método to_s es el símil del método toString de otros lenguajes de programación. Este método se utiliza para que nos devuelva una cadena de texto, que suele ser la información más relevante del objeto. Si haces una clase Dog vacía y llamas puts en una de sus instancias regresará #<Dog:0x007ffd389b7930>. Tu puedes re-definir este método y en nuestro caso, deberá regresar una representación gráfica de nuestro empleado. Cuando digo re-definir me refiero a que por default todas las clases ya lo tienen, ya que heredan de la clase object (si aún no has visto que quiere decir que una clase hereda de otra, ya lo aprenderás no te preocupes). Que métodos deben ser públicos? De los siguientes tres métodos decide cual de ellos solamente tiene sentido que se conozca internamente y cuales deben de ser públicos. def coefficient coefficients = { 1 => 0...1_000, 1.2 => 1_000...2_000, 1.4 => 2_000...5_000, 1.5 => 5_000..10_000 } coefficients.find { |coefficient, range| range.include? @salary }.first end def vacation_days coefficient * 7 end def bonus coefficient * 1000 end Haz pasar el driver code employee = Employee.new('Juan Perez', '[email protected]', 1_800, '123-456-512') employee.to_s # => "Juan Perez <email: [email protected]> acct: *****6512" str = "The employee information is #{employee}" puts str # => "The employee information is Juan Perez <email: [email protected]> acct: *****6512" puts str == "The employee information is Juan Perez <email: [email protected]> acct: *****6512" puts employee.vacation_days == 8.4 puts employee.bonus == 1_200 =end class Employee def vacation_days coefficient * 7 end def bonus coefficient * 1000 end def initialize (name, email, salary, deposit_account) @name = name @email = email @salary = salary @deposit_account = deposit_account.gsub!("-","") end def to_s uncensored = @deposit_account =~ /[^\d]*\d{4}$/ length = @deposit_account.length - 1 acc = $`.gsub!(/\d/,"*") + @deposit_account[uncensored..length] "#{@name} <email: #{@email}> acct: #{acc}" end private def coefficient coefficients = { 1 => 0...1_000, 1.2 => 1_000...2_000, 1.4 => 2_000...5_000, 1.5 => 5_000..10_000 } coefficients.find { |coefficient, range| range.include? @salary }.first end end # driver code employee = Employee.new('Juan Perez', '[email protected]', 1_800, '123-456-512') employee.to_s # => "Juan Perez <email: [email protected]> acct: *****6512" str = "The employee information is #{employee}" puts str # => "The employee information is Juan Perez <email: [email protected]> acct: *****6512" puts str == "The employee information is Juan Perez <email: [email protected]> acct: *****6512" puts employee.vacation_days == 8.4 puts employee.bonus == 1_200
true
39cfae8ad8e304a48bde7db762c5fbaa6363621f
Ruby
deild/RubyOnRailsEtudeDeCas
/e1/depot_ws/app/controllers/login_controller.rb
UTF-8
2,362
2.875
3
[ "MIT" ]
permissive
#--- # Excerpted from "Ruby on Rails, 2nd Ed." # We make no guarantees that this code is fit for any purpose. # Visit http://www.editions-eyrolles.com/Livre/9782212120790/ for more book information. #--- # This controller performs double duty. It contains the # #login action, which is used to log in administrative users. # # It also contains the #add_user, #list_users, and #delete_user # actions, used to maintain the users table in the database. # # The LoginController shares a layout with AdminController # # See also: User class LoginController < ApplicationController layout "admin" # You must be logged in to use all functions except #login before_filter :authorize, :except => :login # The default action displays a status page. def index @total_orders = Order.count @pending_orders = Order.count_pending end # Display the login form and wait for user to # enter a name and password. We then validate # these, adding the user object to the session # if they authorize. def login if request.get? session[:user_id] = nil @user = User.new else @user = User.new(params[:user]) logged_in_user = @user.try_to_login if logged_in_user session[:user_id] = logged_in_user.id redirect_to(:action => "index") else flash[:notice] = "Invalid user/password combination" end end end # Add a new user to the database. def add_user if request.get? @user = User.new else @user = User.new(params[:user]) if @user.save redirect_to_index("User #{@user.name} created") end end end # Delete the user with the given ID from the database. # The model raises an exception if we attempt to delete # the last user. def delete_user id = params[:id] if id && user = User.find(id) begin user.destroy flash[:notice] = "User #{user.name} deleted" rescue flash[:notice] = "Can't delete that user" end end redirect_to(:action => :list_users) end # List all the users. def list_users @all_users = User.find(:all) end # Logout by clearing the user entry in the session. We then # redirect to the #login action. def logout session[:user_id] = nil flash[:notice] = "Logged out" redirect_to(:action => "login") end end
true
04bee5ccee9d168815dd128d07bc2df03582845b
Ruby
yuuki920/freemarket_sample_75b
/app/models/address.rb
UTF-8
1,194
2.59375
3
[]
no_license
class Address < ApplicationRecord belongs_to :user validates :first_name, presence: true, format:{ with: /\A[ぁ-んァ-ン一-龥]/ } validates :last_name, presence: true, format:{ with: /\A[ぁ-んァ-ン一-龥]/ } validates :first_name_reading, presence: true, format: { with: /\A[ァ-ヶー-]+\z/ } validates :last_name_reading, presence: true, format: { with: /\A[ァ-ヶー-]+\z/ } validates :zip_code, presence: true, format: { with: /\A\d{3}[-]\d{4}\z/ } validates :prefectures, presence: true validates :city,presence: true end # バリデーション # 名前 --- 全角ひらがな、カタカナ、漢字 # 名前(よみ) --- 全角カタカナ # 郵便番号 --- [3桁の数字]-[4桁の数字]
true
d17ffd144a7694724aaf35bd3186540ada3b67db
Ruby
rattle/diffrenderer
/lib/word_run_diff_lcs.rb
UTF-8
1,398
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module WordRunDiffLCS class WordRunContextChange attr_reader :action, :old_element, :new_element def initialize(change_context) @action = change_context.action @old_element = change_context.old_element @new_element = change_context.new_element end def merge!(change_context) return false unless merge_possible_with?(change_context) @old_element << " #{change_context.old_element}" if change_context.old_element @new_element << " #{change_context.new_element}" if change_context.new_element true end private def merge_possible_with?(other) return true if action == other.action return true if action == "!" && other.action != "=" false end end class WordRunContextChangeSequence def initialize @word_run_context_changes = [ ] end def <<(diff_lcs_context_change) word_run_context_change = WordRunContextChange.new(diff_lcs_context_change) if empty? @word_run_context_changes << word_run_context_change else @word_run_context_changes << word_run_context_change unless last.merge!(word_run_context_change) end end def map(&block) @word_run_context_changes.map(&block) end private def empty? @word_run_context_changes.empty? end def last @word_run_context_changes.last end end end
true
48ee77ee465bca06bbf270c62610e7946efd3554
Ruby
karlwitek/launch_school_rb130
/ruby_foundations_exer/easy2/each_with_index.rb
UTF-8
1,585
4.5625
5
[]
no_license
# The Enumerable#each_with_index method iterates over the members of a collection, passing # each element and its index to the associated block. The value returned by the block is not used. # #each_with_index returns a reference to the original collection. # Write a method called each_with_index that behaves similarly for arrays. Takes an array as an # argument, and a block. It should yield each element and an index to the block. The method should # return a reference to the original array. # example: # result = each_with_index([1, 3, 6]) do |value, index| # puts "#{index} -> #{value**index}" # end # puts result == [1, 3, 6] # should return: # 0 -> 1 # 1 -> 3 # 2 -> 36 # true def each_with_index(array) index = 0 array.each do |element| yield(element, index)# note the order is important (matches order of block parameters in block below) index += 1 end array end result = each_with_index([1, 3, 6]) do |value, index| puts "#{index} -> #{value**index}" end puts result == [1, 3, 6] # 0 -> 1 # 1 -> 3 # 2 -> 36 # true # LS: (same, EXCEPT FOR RETURN VALUE) # def each_with_index(array) # index = 0 # array.each do |item| # yield(item, index) # index += 1 # end # end # Uses each to iterate through the array, while maintaining an index value that can be passed with the # element value to the block. # In LS solution , the return value is last statement executed (the each loop), and each returns the # array that it is used on, so the return value is array, just what we need.
true
fa38916b1d524e2230026365b71f5e518a91a60f
Ruby
Dwire/jukebox-cli-prework
/lib/jukebox.rb
UTF-8
1,444
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
songs = [ "Phoenix - 1901", "Tokyo Police Club - Wait Up", "Sufjan Stevens - Too Much", "The Naked and the Famous - Young Blood", "(Far From) Home - Tiga", "The Cults - Abducted", "Phoenix - Consolation Prizes", "Harry Chapin - Cats in the Cradle", "Amos Lee - Keep It Loose, Keep It Tight" ] # def say_hello(user_name) # puts "Hello, #{user_name}" # end # # # puts "What is your name?" # name = gets.chomp # # say_hello(name) def help puts "I accept the following commands: - help : displays this help message - list : displays a list of songs you can play - play : lets you choose a song to play - exit : exits this program" end def list(song_list) song_list.each_with_index {|item, index| p "#{index + 1}. #{item}"} end def play(song_list) puts "Please enter a song name or number:" user_input = gets.chomp if song_list.include?(user_input) puts "Playing #{user_input}" elsif user_input.to_i < song_list.length && user_input.to_i > 0 puts "Now Playing: #{song_list[user_input.to_i - 1]}" else puts "Invalid input, please try again" end end def exit_jukebox puts "Goodbye" end def run(songs) help puts "\nPlease enter a command:" user_input = gets.chomp case user_input when "help" run(songs) when "list" list(songs) when "play" play(songs) when "exit" exit_jukebox else run(songs) end end # help # list(songs) # play(songs) # run(songs)
true
eaeee48f94eea66f28802828aa4080d26b2efdc5
Ruby
Videmor/TestingRoR
/clase2/non_duplicate_values/lib/non_duplicate_values.rb
UTF-8
61
2.84375
3
[]
no_license
def non_duplicate(ar) ar.select{|v| ar.count(v) == 1} end
true
bd74c767cf4868510faf1ffef3af4ed74497dc81
Ruby
danclark1820/TDD_challange
/taxes/taxes.rb
UTF-8
801
3.359375
3
[]
no_license
require 'csv' require 'pry' class Citizen attr_reader :first_name, :last_name, :annual_income, :tax_paid, :tax_rate def initialize(first_name, last_name, annual_income, tax_paid, tax_rate) @first_name = first_name @last_name = last_name @annual_income = annual_income @tax_paid = tax_paid @tax_rate = tax_rate end def tax_refund @refund = @tax_paid - @annual_income*(@tax_rate*0.01) end end CSV.foreach('../taxes.csv', headers: true) do |row| row = Citizen.new(row[0], row[1], row[2].to_f, row[3].to_f, row[4].to_f) if row.tax_refund > 0 puts "#{row.first_name} #{row.last_name} will recieve a refund of $#{"%0.2f" % row.tax_refund}" else puts "#{row.first_name} #{row.last_name} owes $#{"%0.2f" % row.tax_refund.abs} in tax" end end
true
3427b476b13c7f3dc8244011537c6aee9627afa9
Ruby
NicholasRostov/object_oriented_ruby
/store_item.rb
UTF-8
430
3.078125
3
[]
no_license
# Some of your store items are food, which have a shelf life. Create a class called Food which inherits from your original class and has an additional property of shelf_life. captain_munch = {sugar_content: "24mlg", color: "Purple", milk_fusion: "mild"} cinnamon_waffle = { :sugar_content => "50mlg", :color => "Brown", :milk_fusion => "extreme"} apple_franks = {sugar_content: "20mlg", color: "Red/Blue", milk_fusion: "none"}
true
f1ff0b27059906c4b05e3b0d4354c571d1845889
Ruby
Fish-bowl/garbage_80s_game
/ex15.rb
UTF-8
493
3.453125
3
[]
no_license
#this line creates and crequires an argument ie. filename filename = ARGV.first #opens txt doc specified by user input "filename" txt = open(filename) #prints note and user input puts "Here's your file #{filename}:" #prints user selected txt. doc print txt.read #re asks for filename print "Type the filename again: " #collects user input file_again = $stdin.gets.chomp #opens new but old "text_again" txt. files txt_again = open(file_again) #shows user selected txt. doc print txt_again.read
true
2f1ce0ea259e1f94fda980f009dc202a4950676b
Ruby
aniagonzalez/tunes-takeout
/app/controllers/suggestions_controller.rb
UTF-8
3,240
2.8125
3
[]
no_license
require_relative '../../lib/TunesTakeoutWrapper.rb' require 'yelp' require 'httparty' class SuggestionsController < ApplicationController #skip before action def index #shows top 20 suggestions, ranked by total number of favorites suggestion_ids = TunesTakeoutWrapper.top["suggestions"] #this should return array of sugg ids @pairings = [] suggestion_ids.each do |suggestion_id| suggestion_object = TunesTakeoutWrapper.find(suggestion_id) suggestion = suggestion_object["suggestion"] yelp_id = suggestion["food_id"] spotify_id = suggestion["music_id"] spotify_type = suggestion["music_type"] if current_user favorite = is_favorite?(suggestion["id"]) end array = [] array << Food.find(yelp_id) #first thing in array is yelp array << Music.find(spotify_id, spotify_type) #second thing is music array << suggestion["id"] if favorite array << favorite end @pairings << array end end def search_by_term #Returns a hash from the TunesTakeoutWrapper end def display_results results = TunesTakeoutWrapper.search(params[:term]) suggestions = results["suggestions"] @pairings = [] suggestions.each do |suggestion| yelp_id = suggestion["food_id"] spotify_id = suggestion["music_id"] spotify_type = suggestion["music_type"] favorite = is_favorite?(suggestion["id"]) array = [] array << Food.find(yelp_id) #first thing in array is yelp array << Music.find(spotify_id, spotify_type) #second thing is music array << suggestion["id"] array << favorite @pairings << array end end def favorite #adds a suggestion into the favorite list for the signed-in User. This requires interaction with the Tunes & Takeout API. TunesTakeoutWrapper.add_favorite(current_user.uid, params[:suggestion_id]) redirect_to root_path end def unfavorite #removes a suggestion from the favorite list for the signed-in User. This requires interaction with the Tunes & Takeout API TunesTakeoutWrapper.remove_favorite(current_user.uid, params[:suggestion_id]) redirect_to root_path end def is_favorite?(suggestion_id) favorites_response = TunesTakeoutWrapper.favorites(current_user.uid) user_favorites = favorites_response["suggestions"] #an array return user_favorites.include? suggestion_id end def favorites favorites_response = TunesTakeoutWrapper.favorites(current_user.uid) suggestion_ids = favorites_response["suggestions"] #this is array of suggestion_ids @pairings = [] suggestion_ids.each do |suggestion_id| suggestion_object = TunesTakeoutWrapper.find(suggestion_id) suggestion = suggestion_object["suggestion"] yelp_id = suggestion["food_id"] spotify_id = suggestion["music_id"] spotify_type = suggestion["music_type"] favorite = is_favorite?(suggestion["id"]) array = [] array << Food.find(yelp_id) #first thing in array is yelp array << Music.find(spotify_id, spotify_type) #second thing is music array << suggestion["id"] array << favorite @pairings << array end end end
true
3331839229efa8594398122b6e6789ef896ab1f3
Ruby
timothyekl/web-oneshot
/wos.rb
UTF-8
3,807
2.8125
3
[]
no_license
#!/usr/bin/env ruby require 'base64' require 'optparse' require 'pp' require 'socket' PBAR_AVAILABLE = require 'progressbar' @options = {} DEFAULT_PORT = 8080 CHUNK_SIZE = 4096 module Helpers # Define loggers def log_verbose(s) if @options[:verbose] == true puts s end end def result(status, sock) puts "#{Time.now.to_i}: #{sock.peeraddr(true)[2]} (#{sock.peeraddr[3]}) ==> #{status}" end # Define authentication helper(s) def accept_auth(user, pass) [@options[:user], @options[:pass]] == [user, pass] end end include Helpers # Parse arguments OptionParser.new do |opts| opts.banner = "Usage: wos.rb [options]" opts.on("-v", "--verbose", "Be verbose") do |v| @options[:verbose] = v end opts.on("-s", "--serve-self", "Serve the wos.rb script file") do |s| @options[:serve_self] = s end @options[:port] = DEFAULT_PORT opts.on("-p", "--port [PORT]", "Use a specific port") do |p| if p.to_i.to_s == p && p.to_i < 65536 && p.to_i > 0 @options[:port] = p.to_i end end opts.on("-U", "--user [USER]", "Require user for authentication") do |u| @options[:user] = u end opts.on("-P", "--pass [PASSWORD]", "Require password for authentication") do |p| @options[:pass] = p end end.parse! # Require a file to serve if ARGV.length != 1 && !(ARGV.length == 0 && @options[:serve_self] == true) $stderr.puts "No file specified and --serve-self option not passed; aborting" Kernel.exit end if @options[:serve_self] == true @options[:file_path] = "wos.rb" else @options[:file_path] = ARGV[0] end class WOS def initialize(opts) @options = opts end def serve! log_verbose("Serving file #{File.size(@options[:file_path])} bytes large") # Open Web server serv = TCPServer.new(@options[:port]) puts "Listening on port #{@options[:port]}" while s = serv.accept # Read HTTP request req = [] while l = s.gets req.push l if l == "\r\n" break end end log_verbose("#{s.peeraddr[2]}: #{req[0]}") served = false # Fetch username/pass out of request user = nil pass = nil req.each do |r| if r[/^Authorization: Basic /] == "Authorization: Basic " auth_b64 = /^Authorization: Basic (.*)$/.match(r)[1] auth = Base64.decode64(auth_b64) user = auth.split(":")[0] pass = auth.split(":")[1] log_verbose("Credentials: #{user} : #{pass}") end end # Parse file from request; redirect if necessary req_file = req[0].split(" ")[1][1..-1] if accept_auth(user, pass) if req_file == File.basename(@options[:file_path]) if !File.exist?(@options[:file_path]) result(404, s) s.print "HTTP/1.1 404/Not Found" else result(200, s) s.print "HTTP/1.1 200/OK\r\n" s.print "Content-Length: #{File.size(@options[:file_path])}\r\n" s.print "\r\n" pbar = ProgressBar.new("sending", (File.size(@options[:file_path]).to_f / CHUNK_SIZE).ceil) if PBAR_AVAILABLE File.open(@options[:file_path]) do |f| while chunk = f.read(CHUNK_SIZE) s.print chunk pbar.inc if PBAR_AVAILABLE end end pbar.finish if PBAR_AVAILABLE end s.close break else result(301, s) s.print "HTTP/1.1 301/Moved Permanently\r\nLocation: #{File.basename(@options[:file_path])}\r\n\r\n" end else result(401, s) s.print "HTTP/1.1 401/Unauthorized\r\nWWW-Authenticate: basic\r\n\r\n" end end end end if __FILE__ == $0 wos = WOS.new(@options).serve! end
true
70afeb30aa9b1c7e9ee6da66cf091b1be3c2a670
Ruby
lovebread/iyxzone_my
/vendor/plugins/acts_as_rateable/lib/acts_as_rateable.rb
UTF-8
870
2.546875
3
[ "MIT" ]
permissive
# ActsAsRateable # the origin plugin is out-of-date and is full of some useless methods # author: 高毛 module Rateable def self.included(base) base.extend(ClassMethods) end module ClassMethods def acts_as_rateable opts={} has_many :ratings, :as => 'rateable', :dependent => :destroy include Rateable::InstanceMethods extend Rateable::SingletonMethods end end module SingletonMethods end module InstanceMethods def create_rating attrs rating = ratings.find_by_user_id(attrs[:user_id]) if rating rating.update_attribute('rating', attrs[:rating]) else ratings.create(:user_id => attrs[:user_id], :rating => attrs[:rating]) end end def find_rating_by_user user ratings.find_by_user_id(user.id) end def rated_by_user? user !ratings.find_by_user_id(user.id).nil? end end end
true
23178373a498ce927980ff4cd4f26fc56583ee40
Ruby
fuCtor/london-bot
/lib/report_downloader.rb
UTF-8
562
2.734375
3
[]
no_license
class ReportDownloader attr_reader :url require 'open-uri' require 'net/http' def initialize(url) @url = url end def download(target) uri = get_file_uri FileUtils.mkdir_p File.dirname(target) Net::HTTP.start(uri.host) do |http| resp = http.get(uri.path) open(target, "wb") do |file| file.write(resp.body) end end target end def get_file_uri doc = Nokogiri::HTML(open(url)) container = doc.css('#objectTtl').first.next.next.next URI.parse container.css('a').first['href'] end end
true
c6b07f1d78bcb916b7b400926bf75d46c67367f5
Ruby
teja318/ecommerce
/faker.rb
UTF-8
396
2.546875
3
[]
no_license
require 'faker' 10.times do category = Category.new({"name" => Faker::Commerce.department(1)}) category.save end 50.times do product = Product.new({"name" => Faker::Commerce.product_name, "price" => Faker::Commerce.price(50..10000), "description" => Faker::Lorem.sentence, "category_id" => Category.all.sample.id, "available" => Faker::Boolean.boolean}) product.save end
true
90cb19b39179aea1a0d5427cac568de00b3b77ef
Ruby
GenerationThree/zhangsiyue-rich-ruby
/lib/player.rb
UTF-8
293
2.859375
3
[]
no_license
class Player @status @last_executed def execute(command) @last_executed = command @status = command.execute(self) end def respond(response) @status = response.execute(self) end def get_status @status end def get_last_executed @last_executed end end
true
7c4104a73cc13f19fa3f08c733507d266a47f523
Ruby
NikolaiIvanov/catstars
/test/lib/place_bid_test.rb
UTF-8
838
2.671875
3
[ "MIT" ]
permissive
require "test_helper" require "place_bid" class PlaceBidTest < MiniTest::Test def setup @user = User.create! email: "[email protected]", password: "password" @other_user = User.create! email: "[email protected]", password: "password" @cat = Cat.create! name: "Awesome cat" @auction = Auction.create! value: 100, cat_id: cat.id end def test_it_places_a_bid service = PlaceBid.new( value: 101, user_id: other_user.id, auction_id: auction.id ) service.execute assert_equal 101, auction.current_bid end def test_fails_to_place_same_or_lower_bid service = PlaceBid.new( value: 99, user_id: other_user.id, auction_id: auction.id ) refute service.execute, "Bid should not be placed" end private attr_reader :user, :other_user, :cat, :auction end
true
f5759725c7398768c3defd4d458222457df7e43b
Ruby
davidcelis/ostatus
/lib/ostatus/entry.rb
UTF-8
2,455
2.5625
3
[]
no_license
require_relative 'activity' require_relative 'author' require_relative 'thread' require_relative 'link' module OStatus THREAD_NS = 'http://purl.org/syndication/thread/1.0' # Holds information about an individual entry in the Feed. class Entry < Atom::Entry include Atom::SimpleExtensions add_extension_namespace :activity, ACTIVITY_NS element 'activity:object-type' element 'activity:object', :class => OStatus::Author element 'activity:verb' element 'activity:target' add_extension_namespace :thr, THREAD_NS element 'thr:in-reply-to', :class => OStatus::Thread # This is for backwards compatibility with some implementations of Activity # Streams. It should not be used, and in fact is obscured as it is not a # method in OStatus::Activity. element 'activity:actor', :class => OStatus::Author namespace Atom::NAMESPACE element :title, :id, :summary element :updated, :published, :class => DateTime, :content_only => true element :source, :class => Atom::Source elements :links, :class => OStatus::Link elements :categories, :class => Atom::Category element :content, :class => Atom::Content element :author, :class => OStatus::Author def activity Activity.new(self) end def activity= value if value.object_type self.activity_object_type = OStatus::Activity::SCHEMA_ROOT + value.object_type.to_s end self.activity_object = value.activity_object if value.object if value.verb self.activity_verb = OStatus::Activity::SCHEMA_ROOT + value.activity_verb.to_s end self.activity_target = value.activity_target if value.target end def url if links.alternate links.alternate.href elsif links.self links.self.href else links.map.each do |l| l.href end.compact.first end end def url= value links << Atom::Link.new(:rel => "alternate", :href => value) end def link links.group_by { |l| l.rel.intern } end def link= options links.clear << Atom::Link.new(options) end # Returns a Hash of all fields. def info { :activity => self.activity.info, :id => self.id, :title => self.title, :content => self.content, :link => self.link, :published => self.published, :updated => self.updated } end end end
true
d036233f1570eb9273cce4181fb6540caece5283
Ruby
fbongiovanni29/ruby_basics
/wrkshp.rb
UTF-8
412
4.0625
4
[]
no_license
def america(x) puts x + "Only in America!" end puts america("Cheesebugers are "); nuArray = [1, 3, 2] organized_array = nuArray.sort puts organized_array def max_num(n) n.sort puts n[n.length - 1] end n = [2, 3, 1, 6, 7] max_num(n) def cars(make, model) car = {make[0] => model[0], make[1] => model[1]} end make = [:toyota, :tesla] model = ["Prius", "Model S"] puts cars(make, model)
true
a930bb0952b39d326c9421578e9c35850e13c94e
Ruby
mmbensalah/scrabble_web_api
/spec/requests/games_request_spec.rb
UTF-8
1,327
2.90625
3
[]
no_license
require "rails_helper" describe "Games API" do # it "returns all games" do # josh = User.create(id: 1, name: "Josh") # sal = User.create(id: 2, name: "Sal") # # game = Game.create(id: 1, player_1: josh, player_2: sal) # # get "/api/v1/games/1" # # expect(response).to be_successful # game = JSON.parse(response.body) # expect(game["id"]).to eq(1) # expect(game["player_1_id"]).to eq(1) # expect(game["player_2_id"]).to eq(2) # end it "returns games w/ scores" do josh = User.create(id: 1, name: "Josh") sal = User.create(id: 2, name: "Sal") game = Game.create(id: 1, player_1: josh, player_2: sal) josh.plays.create(game: game, word: "sal", score: 3) josh.plays.create(game: game, word: "zoo", score: 12) sal.plays.create(game: game, word: "josh", score: 14) sal.plays.create(game: game, word: "no", score: 2) get "/api/v1/games/1" expect(game["game_id"]).to eq(1) expect(game["scores"][0]["user_id"]).to eq(1) expect(game["scores"][0]["score"]).to eq(14) expect(game["scores"][1]["user_id"]).to eq(2) expect(game["scores"][1]["score"]).to eq(16) end end # { # "game_id":1, # "scores": [ # { # "user_id":1, # "score":15 # }, # { # "user_id":2, # "score":16 # } # ] # }
true
287a023cd49ac168504cc9e20410a38178df1166
Ruby
KevinNorth/Kevbot
/src/commands/nsfw.rb
UTF-8
2,092
3.046875
3
[ "MIT" ]
permissive
require_relative '../kevbot_state.rb' require_relative 'command.rb' class NsfwCommand include Command # Returns an array of strings that can be used as command names in the chat. def names() names = [] names.push "nsfw" return names end # execute(string) - return nothing # Submits a complaint that a song is innapropriate. # Skips the current song if enough people have complained. def execute(parameter, user, client, state) room = client.room complainers = state.nsfw_complainers num_listeners = room.listeners.size if room.current_song unless complainers.include? user complainers.push user case num_listeners when 2 # The only users are the robot and the complainer room.say "You're the only one in here." room.say "I promise you can't offend me. I'm a robot." when 3 # One listener room.say "@#{room.current_dj.name}, nsfw music is not allowed in this room. Please skip your song." else # Multiple listeners num_complainers = complainers.size complaint_limit = calculate_complaint_limit(num_listeners) if num_complainers >= complaint_limit room.current_song.skip else room.say "If #{complaint_limit - num_complainers} more people complain, I'll skip the song." end end end end end # Calculates how many people need to complain about a song # before it will be skipped def calculate_complaint_limit(num_listeners) num_listeners -= 2 # don't count the DJ and the bot case num_listeners when 2 return 2 when 3..5 return 3 when 6..7 return 4 when 8..14 return 5 when 15..20 return 6 else return num_listeners / 3 end end # help_message() - return a string # Returns a message that can be used with the `help` command to describe what the command does to users. def help_message() return "If enough users use /nsfw on this song, I'll skip it for being not safe for work." end end
true
46dedca4039d1f668bb4c98b5ba0b8b07fb2e517
Ruby
DMscotifer/wk2_day1_homework
/partBhomework.rb
UTF-8
696
3.125
3
[]
no_license
class Sports_Team attr_accessor :team_name, :player_names, :coach, :points def initialize(team_name, player_names, coach, points) @team_name = team_name @player_names = player_names @coach = coach @points = points end # # def get_team_name # @team_name = team_name # end # # def get_player_names # @player_names = player_names # end # # def get_coach_name # @coach = coach # end def set_coach_name(name) @coach = name end def add_player(player) @player_names.push(player) end def find_player_name(player_name) for player in @player_names return true if player == player_name end end def win_lose(outcome) @points += 1 if outcome == "win" end end
true
bf83576d7c6527cf38c8fd9d40f9dfed21e9b7b9
Ruby
alejandracampero/ttt-7-valid-move-bootcamp-prep-000
/lib/valid_move.rb
UTF-8
485
3.6875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# code your #valid_move? method here board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def valid_move? (board, index) if index.between?(0,8) && position_taken?(board, index) == false true end end # re-define your #position_taken? method here, so that you can use it in the #valid_move? method above. def position_taken? (board, index) taken = nil if (board [index] == " " || board [index] == "" || board [index] == nil) taken = false else taken = true end end
true
4187282b8d7b1b543387293285f8d1b68ad40d85
Ruby
stef-codes/ruby-enumerables-hash-practice-green-grocer-lab-online-web-prework
/grocer.rb
UTF-8
1,269
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def consolidate_cart(cart) cart_hash = {} count = 0 cart.map do |element| element.each do |fruit,hash| cart_hash[fruit] ||= hash cart_hash[fruit][:count] ||= 0 cart_hash[fruit][:count] += 1 end end cart_hash end def apply_coupons(cart, coupons) coupons.each do |coupon| item = coupon[:item] if cart[item] if cart[item] && cart[item][:count] >= coupon[:num] && !cart.has_key?("#{item} W/COUPON") cart["#{item} W/COUPON"] = {price: coupon[:cost]/coupon[:num], clearance: cart[item][:clearance], count:coupon[:num]} cart[item][:count] -= coupon[:num] elsif cart[item][:count] >= coupon[:num] && cart.has_key?("#{item} W/COUPON") cart["#{item} W/COUPON"][:count] += coupon[:num] cart[item][:count] -= coupon[:num] end end end cart end def apply_clearance(cart) cart.map do |product_name, stats| stats[:price] -= stats[:price] * 0.2 if stats[:clearance] end cart end def checkout(cart,coupons) hash_cart = consolidate_cart(cart) applied_coupons = apply_coupons(hash_cart,coupons) applied_discount = apply_clearance(applied_coupons) total = applied_discount.reduce(0) {|acc, (key,value)| acc += value[:price]*value[:count]} total > 100 ? total * 0.9 : total end
true
096cc467e7dee1266c3f68b00653ba07577b1aa7
Ruby
colinrubbert/course_work
/firehose/prework/ch4/inches.rb
UTF-8
120
3.640625
4
[]
no_license
puts "Enter a legth in inches" inches = gets.chomp cent = inches.to_f * 2.54 puts "#{inches} is #{cent} in centimeters."
true
294ee2189b7f210f812a641e79ca58a25e9882d4
Ruby
ChengHsuanLiu/FastekReport
/parser/annual_report_generator.rb
UTF-8
5,655
2.90625
3
[]
no_license
########################## ## 年度業績報表 ########################## ## 使用方法 ## 呼叫程式,後面帶參數譬如 2016.csv, 2017.csv, ## 每個檔案是該年度的年度進銷報表 ## ex. ruby parser/annual_report_generator.rb 2016.csv 2017.csv ## 產品分類 # E 電動缸 / 音圈馬達 # K 光電類 # I 點膠類 # P 馬達 Hanmark / TOYO / DELTA # L 光寶 # 分公司 # 桃園總公司 # 台北:光鈦-台北 # 中壢:光鈦-中壢 # 新竹:光鈦-(竹鈦) # 台中:光鈦-台中 # 台南:光鈦-台南 # 高雄:光鈦高雄 require 'csv' require 'spreadsheet' Spreadsheet.client_encoding = 'UTF-8' excelName = Time.now.strftime "年報表%Y-%m-%d-%H-%M-%S" book = Spreadsheet::Workbook.new format = Spreadsheet::Format.new :color => :black, :size => 16, :vertical_align => :middle color_column_fmt = Spreadsheet::Format.new :pattern => 1, :pattern_fg_color => :gray, :vertical_align => :middle, :size => 16, :align => :center, :color => :white sheet = book.create_worksheet :name => '年報表' sheet.default_format = format sheet[0,0] = "群組欄位" sheet[0,1] = "索引名稱" sheet[0,2] = "各分公司" sheet.row(0).set_format(0, color_column_fmt) sheet.row(0).set_format(1, color_column_fmt) sheet.row(0).set_format(2, color_column_fmt) if( ARGV[0].nil? || ARGV[0].empty? || ARGV.length == 0 ) return false end def default_data return { "光鈦-桃園" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦-台北" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦-中壢" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦-(竹鈦)" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦-台中" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦-台南" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 }, "光鈦高雄" => { "E" => 0, "K" => 0, "I" => 0, "P" => 0, "L" => 0 } } end result = Hash.new companies = ["光鈦-台北", "光鈦-中壢", "光鈦-(竹鈦)", "光鈦-台中", "光鈦-台南", "光鈦高雄"] allCompanies = ["光鈦-桃園", "光鈦-台北", "光鈦-中壢", "光鈦-(竹鈦)", "光鈦-台中", "光鈦-台南", "光鈦高雄", "小計"] categoryCodes = ["E", "I", "K", "P", "L"] categoryName = ["電動缸、音圈馬達", "點膠類", "光電類", "馬達HANMARK、TOYO、DELTA", "光寶"] ARGV.each_with_index do |fileName, index_1| result[fileName] = default_data sheet[0,(index_1 + 3)] = fileName.gsub('.csv', '') sheet.row(0).set_format((index_1 + 3), color_column_fmt) annualTotal = 0 # fileName ex. 2016.csv CSV.foreach("source/#{fileName}", headers: true, encoding: "UTF-8").with_index do |row, index_2| # if index_2 < 3 sellDate = row[3].strip quantity = row[7].strip singlePrice = row[9].strip singlePriceTotal = row[10].to_s.gsub(',', '').to_i clientName = row[13].strip categoryCode = row[18].strip puts "#{sellDate} #{singlePriceTotal} #{clientName} #{categoryCode}" begin if (categoryCodes.include? categoryCode) if (companies.include? clientName) originTotal = result[fileName][clientName][categoryCode].to_i afterTotal = originTotal + (singlePriceTotal || 0).to_i result[fileName][clientName][categoryCode] = afterTotal else originTotal = result[fileName]["光鈦-桃園"][categoryCode].to_i afterTotal = originTotal + (singlePriceTotal || 0).to_i result[fileName]["光鈦-桃園"][categoryCode] = afterTotal end end rescue Exception => e puts e end # end end puts result categoryCodes.each_with_index do |cc, index_i| categorySubtotal = 0 allCompanies.each_with_index do |company, index_j| sheet[( index_i*allCompanies.count + (index_j + 1) ), 0] = cc sheet[( index_i*allCompanies.count + (index_j + 1) ), 1] = categoryName[index_i] sheet[( index_i*allCompanies.count + (index_j + 1) ), 2] = company if company == "小計" sheet[( index_i*allCompanies.count + (index_j + 1) ),(index_1 + 3)] = categorySubtotal sheet.row(( index_i*allCompanies.count + (index_j + 1) )).set_format(2, color_column_fmt) sheet.row(( index_i*allCompanies.count + (index_j + 1))).set_format((index_1 + 3), color_column_fmt) else resultTotal = result[fileName][company][cc] sheet[( index_i*allCompanies.count + (index_j + 1)),(index_1 + 3)] = resultTotal categorySubtotal += resultTotal.to_i end end annualTotal += categorySubtotal end sheet[(allCompanies.count*categoryCodes.count + 1), 2] = "總計" sheet[(allCompanies.count*categoryCodes.count + 1), (index_1 + 3)] = annualTotal end # sheet.merge_cells(start_row, start_col, end_row, end_col) sheet.merge_cells(1, 0, 8, 0) sheet.merge_cells(9, 0, 16, 0) sheet.merge_cells(17, 0, 24, 0) sheet.merge_cells(25, 0, 32, 0) sheet.merge_cells(33, 0, 40, 0) sheet.merge_cells(1, 1, 8, 1) sheet.merge_cells(9, 1, 16, 1) sheet.merge_cells(17, 1, 24, 1) sheet.merge_cells(25, 1, 32, 1) sheet.merge_cells(33, 1, 40, 1) sheet.rows.map{|row| row.height = 50 if !row.nil?} for counter in 0..(2 + ARGV.length) sheet.column(counter).width = 30 end book.write "results/#{excelName}.xls"
true
c174eee113ccd3ccfc83a82b5c185f39272a3195
Ruby
rentes/design_patterns_in_ruby
/Structural/Facade/facade.rb
UTF-8
896
3.4375
3
[ "MIT" ]
permissive
# The Subsystem Class A class class CarModel def model puts ' CarModel - model' end end # The Subsystem Class B class class CarEngine def engine puts ' CarEngine - engine' end end # The Subsystem Class C class class CarBody def body puts ' CarBody - body' end end # The Subsystem Class D class class CarAccessories def accessories puts ' CarAccessories - accessories' end end # The Car Facade class class CarFacade attr_reader :model, :engine, :body, :accessories def initialize @model = CarModel.new @engine = CarEngine.new @body = CarBody.new @accessories = CarAccessories.new end def create_complete_car puts '******* Creating a Car ********' @model.model @engine.engine @body.body @accessories.accessories puts '**** Car creation complete ****' end end facade = CarFacade.new facade.create_complete_car
true
9a3fb26b97a85b72b8c1a91d6a1b89074fa31367
Ruby
pranavnawathe/DesignPatternsNew
/ruby/Proxy/movie_player.rb
UTF-8
381
3.046875
3
[]
no_license
#this class acts as Proxy require_relative 'video_functions' class MoviePlayer < VideoFunctions attr_accessor :movie attr_accessor :name def initialize(name) @movie = Movie.new(name) end def playMovie movie.playMovie end def getMovieDetails movie.getMovieDetails end def deleteMovie puts "\nPermission denied!" end end
true
021c25e8a27dcd4eef7787fd3ee072f21f9994b6
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz98_sols/solutions/benchmark/proof.rb
UTF-8
396
3.484375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby -w require "sorted_array" # Daniel's PriorityQueue require "heap" # pure Ruby Heap, from Ruby Quiz #40 DATA = Array.new(5_000) { rand(5_000) }.freeze queue1, queue2 = PriorityQueue.new, Heap.new DATA.each do |n| queue1.add(n, n) queue2.insert(n) end until queue1.empty? raise "Mismatch!" unless queue1.next == queue2.extract end puts "All values matched."
true
ca6655f157bf47166bf32676bdda5a7ac5d62a6f
Ruby
kibex92/Pocket-Reader
/lib/services/reader_scraper.rb
UTF-8
1,613
2.890625
3
[]
no_license
require 'open-uri' require 'nokogiri' class ReaderScraper attr_reader :post_path URL = "https://dev.to/" def initialize(post_path) @post_path = post_path @posts_view = PostsView.new end def call post = scrape_post author = scrape_author { post: post, author: author } end private def scrape_page begin html = URI.open("#{URL}#{@post_path}") Nokogiri::HTML(html) rescue OpenURI::HTTPError => e handle_error(e) end end def scrape_post params = { path: @post_path } doc = scrape_page params[:title] = doc.search('h1').first.children.text.strip paragraphs = doc.search('.crayons-article__main p') params[:content] = paragraphs.map do |element| element.text.strip end.join("\n\n") Post.new(params) end def scrape_author params = Hash.new nickname = @post_path.split('/').first html = URI.open("#{URL}#{nickname}") doc = Nokogiri::HTML(html) params[:description] = doc.search('.crayons-layout p').first.text info = doc.search('.crayons-card--secondary .items-center').map do |e| e.text.strip end params[:nickname] = nickname params[:posts_published] = info.find { |element| element.match?("Post") }.split.-(["Post"]).join(" ") params[:comments_written] = info.find { |element| element.match?("Comment") }.split.-(["Comment"]).join(" ") params[:name] = doc.search(".crayons-title").text.strip Author.new(params) end def handle_error(e) puts "404 Not found" @post_path = @posts_view.ask_for("Another path") scrape_page end end
true
df5548911c9fda84769cf7e2d220c4066754f5cb
Ruby
jKwibe/backend_module_0_capstone
/day_7/checker_board.rb
UTF-8
764
3.859375
4
[]
no_license
## Better Way => Dynamic Solution class CheckerBoard def checker_board(board_size) puts "Checker Board" x_columns = [] space_columns =[] i = 0 j = 0 # pushing values to the x_columns and space_columns arrays until i == board_size i += 1 if i.odd? #The same as if i % 2 != 0 x_columns << "X" space_columns << " " # alternative of push => << else x_columns << " " space_columns << "X" end end x_first_line = x_columns.join space_first_line = space_columns.join until j == board_size j += 1 puts (j.odd?)? x_first_line : space_first_line end end end board = CheckerBoard.new board.checker_board(6)
true
59cb208a3e869397b61d5ebb12b825b698ae41b6
Ruby
odsod/gb
/scripts/generate-disassembler
UTF-8
9,306
2.515625
3
[]
no_license
#!/usr/bin/env ruby require 'json' require 'open3' class LD def initialize(i) @opcode = i['opcode'] @mnemonic, @cycles = i['implementation'].values_at('mnemonic', 'cycles') end def load_value case @mnemonic when /,\((a8|C)\)$/ # Zero page "value := cpu.memory.Read(mmu.ZeroPage.AddressOf(cpu.#{$1}()))" when /,([^()+-]+)$/ # Non-pointer "value := cpu.#{$1}()" when /,\(HL([+-])\)$/ # HL with inc/dec "value := cpu.memory.Read(cpu.HL#{$1 == '+' ? 'I' : 'D'}())" when /,\((.+)\)$/ # Pointer "value := cpu.memory.Read(cpu.#{$1}())" else raise "Unhandled: #{@mnemonic}" end end def store_value case @mnemonic when / ([^()]+),/ # Non-pointer "cpu.Set#{$1}(value)" when / \(HL([+-])\),/ # HL with inc/dec "cpu.Write8(cpu.HL#{$1 == '+' ? 'I' : 'D'}(), value)" when / \((a8|C)\),/ # Zero page pointer "cpu.Write8(mmu.ZeroPage.AddressOf(cpu.#{$1}()), value)" when / \(([^+-]+)\),/ # Pointer "cpu.Write8(cpu.#{$1}(), value)" else raise "Unhandled: #{@mnemonic}" end end def to_s "case #{@opcode}: // #{@mnemonic} #{self.load_value} #{self.store_value} return #{@cycles} ".strip.gsub(/\s*$/m, '') end end class Jump def initialize(i) @opcode = i['opcode'] @mnemonic, @cycles = i['implementation'].values_at('mnemonic', 'cycles') end def conditional? @cycles.is_a?(Hash) end def condition case @mnemonic when / (N?)(Z|C)/ "#{'!' if $1 == 'N'}cpu.Flag#{$2}()" else raise "Unhandled: #{@mnemonic}" end end def compute_address case @mnemonic when /^JR .*r8$/ 'address := uint16(int32(cpu.PC()) + int32(cpu.Fetch8()))' when /^RET/ 'address := cpu.Pop16()' when /a16$/ 'address := cpu.Fetch16()' when /^RST (..)H/ "const address = 0x#{$1}" when 'JP (HL)' 'address := cpu.HL()' else raise "Unhandled: #{@mnemonic}" end end def execute_jump case @mnemonic when /^(CALL|RST)/ 'cpu.Push16(cpu.PC()) cpu.SetPC(address)' when /^(JR|JP|RET)/ 'cpu.SetPC(address)' else raise "Unhandled: #{@mnemonic}" end end def to_s if self.conditional? "case #{@opcode}: // #{@mnemonic} if #{self.condition} { #{self.compute_address} #{self.execute_jump} return #{@cycles['branch']} } return #{@cycles['noBranch']} ".strip.gsub(/\s*$/m, '') else "case #{@opcode}: // #{@mnemonic} #{self.compute_address} #{self.execute_jump} return #{@cycles} ".strip.gsub(/\s*$/m, '') end end end class ALU def initialize(i) @opcode = i['opcode'] @mnemonic, @cycles = i['implementation'].values_at('mnemonic', 'cycles') @z, @n, @h, @c = i['implementation']['flags'].values_at('z', 'n', 'h', 'c') end def load_operand1 case @mnemonic when /^(?:INC|DEC) \(HL\)$/ "operand1 := cpu.memory.Read(cpu.HL())" when /^(?:INC|DEC) (.+)$/ "operand1 := cpu.#{$1}()" when / [^,]*$/ # Implicit A "operand1 := cpu.A()" when / (.+),/ "operand1 := cpu.#{$1}()" else raise "Unhandled: #{@mnemonic}" end end def load_operand2 case @mnemonic when /^(INC|DEC)/ 'const operand2 = 1' when /(?:,| )([^,()]+)$/ # Non-pointer "operand2:= cpu.#{$1}()" when /(?: |,)\(HL\)$/ # HL pointer "operand2:= cpu.memory.Read(cpu.HL())" else raise "Unhandled: #{@mnemonic}" end end def compute_result case @mnemonic when /^(ADD|INC)/ 'result := operand1 + operand2' when /^ADC/ 'result := operand1 + operand2 + cpu.Carry()' when /^(SUB|CP|DEC)/ 'result := operand1 - operand2' when /^SBC/ 'result := operand1 - operand2 - cpu.Carry()' when /^AND/ 'result := operand1 & operand2' when /^OR/ 'result := operand1 | operand2' when /^XOR/ 'result := operand1 ^ operand2' else raise "Unhandled: #{@mnemonic}" end end def store_result case @mnemonic when /^(?:INC|DEC) \(HL\)$/ 'cpu.Write8(cpu.HL(), result)' when /^(?:INC|DEC) (.+)$/ "cpu.Set#{$1}(result)" when /^CP / '' # Update flags only when / [^,]*$/ # Implicit A 'cpu.SetA(result)' when / (.+),/ "cpu.Set#{$1}(result)" else raise "Unhandled: #{@mnemonic}" end end def update_zero_flag case when @z.is_a?(Numeric) "cpu.SetFlagZ(#{@z == 1})" when @z "cpu.SetFlagZ(result == 0)" end end def update_subtract_flag case when @n.is_a?(Numeric) "cpu.SetFlagN(#{@n == 1})" when @n "Unhandled: #{@mnemonic}" end end def update_half_carry_flag case when @h.is_a?(Numeric) "cpu.SetFlagH(#{@h == 1})" when @h half_carry = if @n == 1 # Subtraction if @mnemonic =~ /^SBC/ # With carry 'int16(operand1&0x0F) - int16(operand2&0x0F) - int16(cpu.Carry()) < 0' else # Without carry 'int16(operand1&0x0F) - int16(operand2&0x0F) < 0' end else # Addition if @mnemonic =~ /^ADD HL/ # 16-bit 'uint32(operand1&0xFFF) + uint32(operand2&0xFFF) > 0xFFF' elsif @mnemonic =~ /^ADC/ # With carry '(operand1&0x0F) + (operand2&0x0F) + cpu.Carry() > 0x0F' else # Without carry '(operand1&0x0F) + (operand2&0x0F) > 0x0F' end end "cpu.SetFlagH(#{half_carry})" end end def update_carry_flag case when @c.is_a?(Numeric) "cpu.SetFlagC(#{@c == 1})" when @c carry = if @n == 1 # Subtraction if @mnemonic =~ /^SBC/ # With carry 'int16(operand1) - int16(operand2) - int16(cpu.Carry()) < 0' else # Without carry 'int16(operand1) - int16(operand2) < 0' end else # Addition if @mnemonic =~ /^ADD HL/ # 16-bit 'uint32(operand1) + uint32(operand2) > 0xFFFF' elsif @mnemonic =~ /^ADC/ # With carry 'uint16(operand1) + uint16(operand2) + uint16(cpu.Carry()) > 0xFF' else # Without carry 'uint16(operand1) + uint16(operand2) > 0xFF' end end "cpu.SetFlagC(#{carry})" end end def to_s "case #{@opcode}: // #{@mnemonic} #{self.load_operand1} #{self.load_operand2} #{self.compute_result} #{self.store_result} #{self.update_zero_flag} #{self.update_subtract_flag} #{self.update_half_carry_flag} #{self.update_carry_flag} return #{@cycles} ".strip.gsub(/\s*$/m, '') end end class Stack def initialize(i) @opcode = i['opcode'] @mnemonic, @cycles = i['implementation'].values_at('mnemonic', 'cycles') end def to_s op = case @mnemonic when /^PUSH (..)$/ "cpu.Push16(cpu.#{$1}())" when /^POP (..)$/ "cpu.Set#{$1}(cpu.Pop16())" else "Unhandled: #{@mnemonic}" end "case #{@opcode}: // #{@mnemonic} #{op} return #{@cycles} ".strip.gsub(/\s*$/m, '') end end class Unsupported def initialize(i) @opcode = i['opcode'] end def to_s "case #{@opcode}: // Not used panic(\"Unsupported opcode by Sharp LR35902: #{@opcode}\") ".strip.gsub(/\s*$/m, '') end end class Unhandled def initialize(i) @opcode = i['opcode'] @mnemonic = i['implementation']['mnemonic'] end def to_s "case #{@opcode}: // Unhandled: #{@mnemonic} panic(\"Unhandled instruction: #{@mnemonic} (#{@opcode})\") ".strip.gsub(/\s*$/m, '') end end def parse(instruction) if instruction['implementation'].nil? return Unsupported.new(instruction) end case instruction['implementation']['mnemonic'] when 'ADD SP,r8', 'LD HL,SP+r8', 'LD (a16),SP', 'RETI' # Special cases Unhandled.new(instruction) when /^(PUSH|POP)/ Stack.new(instruction) when /^LD/ LD.new(instruction) when /^(CALL|RET|JP|JR|RST)/ Jump.new(instruction) when /^(INC|DEC|ADD|ADC|SUB|SBC|AND|OR|XOR|CP) / ALU.new(instruction) else Unhandled.new(instruction) end end @instruction_set = JSON.parse(File.read(ARGV[0])) @output = " // This file has been generated automatically. Do not edit manually. package disassemble func NextInstruction(pc uint16, rom []byte) (n uint16, instruction string) { opcode := rom[pc] switch opcode { #{@instruction_set['noPrefix'].map do |i| "case #{i['opcode']}: #{ case when i['implementation'].nil? 'return 1, fmt.Sprintf("%#x\t??\t%#x", pc, opcode)' when i['opcode'] == '0xcb' 'return nextCBInstruction(pc + 1, rom)' when i end }" end .map(&:to_s) .map {|s| "\n" + s + "\n" } .join("\n") } default: panic(fmt.Sprintf(\"Opcode unhandled by generated instructions: %#x\", opcode)) } } func cbInstruction(" Open3.popen3('goimports') do |stdin, stdout, stderr, wait_thread| stdin.write @output stdin.close if wait_thread.value == 0 puts stdout.read else puts @output puts stderr.read end end
true
7bc2ca54b214f1d0c650209229883700bf7ceca7
Ruby
mdonagh/ruby-intro
/1.rb
UTF-8
2,264
4.5
4
[]
no_license
# Your assignment is to use the examples below to write a method called "double" which takes an integer parameter # Double it, and return the doubled value. # Then write a test confirming the method works. # Also write a method called add_five with return value and two tests. # Also let me say - I know that there are lots of websites that offer similar curriculum. I think it's better for your own # learning to do everything on your own on your computer rather than let some website curate the experience for you # So that you get the hang of running code # Also to write comments in ruby files just precede them with a hash # ALL OF YOUR WORK HERE - just post either the code or the files in #standup # Variables # Here, an all-inclusive intro to ruby. # On your computer, from the terminal, run irb to open a ruby console. Copy-paste the ruby code in to run it. # Or, run these files with ruby 1.rb . # Variables # printing a name name = "Mark" puts name number = 5 if(number == 5) puts "the number is five" else puts "the number is NOT five" end # Notice that one equals sign assigns a variable, and two checks if the two variables are equal # simple arithmetic sum = 5 + 5 puts sum difference = 10 - 5 puts difference product = 5 * 5 puts product quotient = 5 / 5 puts quotient # This is called a function. Functions take a parameter or argument - "number" # This doesn't return anything, functions return a variable most of the time def is_number_five?(number) if(number == 5) puts "the number is five" else puts "the number is NOT five" end end # Function with return type def is_number_five?(number) if(number == 5) return true else return false end end # Simple testing: # You can see here - the method returns true or false - a "boolean" value. Then, we are checking that against our expectation # To run tests, do the following: # gem install rspec # gem install rspec-expectations # rspec --init # Then, run rspec 1.rb , or rpsec whatever.rb # The hash below means method named is_number_five? describe "#is_number_five?" do it "Should return true" do expect(is_number_five?(5)).to eq(true) end it "Should return false" do expect(is_number_five?(6)).to eq(false) end end
true
c9d2e3a09d326300ee61003f93d25bc5004b3578
Ruby
pickledyamsman/prime-ruby-v-000
/prime.rb
UTF-8
129
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(int) divs = [] (1..int).to_a.each do |i| divs << i if int % i == 0 end divs.length == 2 ? true : false end
true