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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ada752c20b7915417b706b3e5b2657d426ac1381
|
Ruby
|
griswold/shinny
|
/app/helpers/application_helper.rb
|
UTF-8
| 893 | 2.65625 | 3 |
[] |
no_license
|
module ApplicationHelper
def format_activity_time(start_time, end_time)
time_of_day_format = "%-I:%M%P"
start_format = [("%b %-d" unless start_time.to_date == Date.current), time_of_day_format].compact.join(" ")
[start_time.strftime(start_format), "-", end_time.strftime(time_of_day_format)].join(" ")
end
def summarize_search(search)
["Showing #{search.activity.name.downcase}"].tap do |msg|
if search.age.blank? && search.gender.blank?
msg << "for everyone"
else
msg << "for a "
msg << "#{search.age} year old" if search.age.present?
gender = { ScheduledActivity::MALE => "guy", ScheduledActivity::FEMALE => "girl" }[search.gender]
msg << gender if gender.present?
end
msg << (search.distance.present? ? "within #{search.distance}km of" : "near")
msg << search.location
end.join(" ")
end
end
| true |
e126641f8782ddb9125a8e2cafea503b8993fd96
|
Ruby
|
thib123/TPJ
|
/Notes/Ruby/sample_code/ex0008.rb
|
UTF-8
| 89 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# Sample code from Programing Ruby, page 11
number = Math.abs(number) // Java code
| true |
e9fcb26ea3b4f732b9ed938b639b4bc1e9cd6528
|
Ruby
|
thib123/TPJ
|
/Notes/Ruby/sample_code/ex1306.rb
|
UTF-8
| 108 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
# Sample code from Programing Ruby, page 600
"now is the time".sum
"now is the time".sum(8)
| true |
7b97208596d53cebacf4be9961e01ccf83159be3
|
Ruby
|
theldoria/lg-lcd
|
/lib/lg-lcd/open.rb
|
UTF-8
| 566 | 2.609375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require_relative 'lib'
module LgLcd
class Open
def initialize connection
@ctx = Lib::OpenByTypeContext.new
@ctx[:connection] = connection
@ctx[:device_type] = Lib::LGLCD_DEVICE_BW
@ctx[:device] = Lib::LGLCD_INVALID_DEVICE
raise "Open by type failes" unless Lib::LGLCD_RET_OK == Lib.open_by_type(@ctx)
begin
yield(self)
ensure
puts "Close"
Lib.close(@ctx[:device])
end
end
def device
return @ctx[:device]
end
end
end
| true |
14a240e0dc6c99b28215d087b76979d5378ed301
|
Ruby
|
marioatpb/advent_of_code
|
/2016/13/run.rb
|
UTF-8
| 372 | 2.890625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require_relative 'maze'
input = File.read('./input.txt')
ad = Advent::Maze.new(input)
s = ad.steps([31,39])
puts "Steps: #{s}"
ad.debug!
s = ad.steps([31,39], 50)
puts "Locations: #{s}"
# 473 is too high - Did we include 1,1?
# Off by one?a
#
# 460 is too high
# 448 is too high
#
# Probably need to exclude walls
# 217 isn't right... off by one?
| true |
1df5dd1e7382b6371f527274a6bf75a181342a38
|
Ruby
|
nmcguire61/homework_submission
|
/goingdown/person.rb
|
UTF-8
| 237 | 2.96875 | 3 |
[] |
no_license
|
class Person
attr_accessor :name, :weight, :age
#attr_reader
def initialize(options={})
self.name = options[:name]
self.age = options[:age]
self.weight = options[:weight].to_f
end
#attrs: names, destinations
end
| true |
c2e0b87f708416b9ae12533f29257a9aa25c89b1
|
Ruby
|
vinaymehta/Training-2
|
/ruby/qestions/firstelement.rb
|
UTF-8
| 422 | 4.375 | 4 |
[] |
no_license
|
=begin
very easy
Return the First Element in an Array
Create a function that takes an array containing only numbers and return the first element.
Examples
get_first_value([1, 2, 3]) ➞ 1
get_first_value([80, 5, 100]) ➞ 80
get_first_value([-500, 0, 50]) ➞ -500
Notes
The first element in an array always has an index of 0.
=end
def get_first_value(arr)
puts arr[0]
end
get_first_value([1,2,4])
#output : 1
| true |
87cf28e5320d889753a33bef6d989dff03267151
|
Ruby
|
akchalasani1/myruby
|
/examples/learn/disp_array_hash_dup_count1.rb
|
UTF-8
| 2,092 | 4.0625 | 4 |
[] |
no_license
|
# http://gregpark.io/blog/ruby-group-by/
# you can generally use group_by anywhere you’d be using #each or some iteration.
# The collection of objects that needs grouping (e.g., an array)
# group_by returns a hash where the keys are defined by our grouping rule, and the values are the corresponding objects from our original collection.
# {"ind"=>["ind", "ind"], "uk"=>["uk"], "usa"=>["usa", "usa"], "chin"=>["chin"], "rus"=>["rus"]}
#
cntry_code = %w(ind uk usa chin rus ind usa).group_by{|anil|anil}.keep_if{|_, anil| anil.length > 1}
# By convention, underscore is used as a variable name for a value that is not used. Unlike other variable names, it can be used multiple times in a single parallel assignment.
# In this particular case, the filter in the block is not interested in the key of the hash, but only the value of the hash, which is an array generated by group_by.
# A small point: a variation of the convention is to write a variable name that begins with an underscore.
# For example, if h we're a hash, h.each { |_k, v| .. } would signal to the reader that the hash's keys are not used in the block calculation.
p cntry_code.keys
# dup = %w(usa ind uk chin uk ind)
# dup = ["usa", "ind", "chin", "tibet", "usa", "chin", "ind"]
# .group_by{|e| e} groups all similar country's and transfers into new variable 'e', and returns a hash
# ex: {"ind"=>["ind", "ind"], "uk"=>["uk"], "usa"=>["usa", "usa"], "chin"=>["chin"], "rus"=>["rus"]}
# keep_if → Enumerator : Deletes every element of self for which the given block evaluates to false.
# in Ruby .map method is used to transform the contents of an array according specified set of rules
# defined inside the code block K is keys and V is values
country = cntry_code.map{|k, v| {k => v.length}}
# country = dups.map{|a, b| {a => b.count}}
p country
=begin
cheeses = ["muenster", "extra sharp cheddar", "white cheddar", "pepper jack", "beer cheddar"]
puts cheeses.select { |cheese| cheese.include?("cheddar") }
p cheeses.keep_if { |cheese| cheese.include?("cheddar") }
p cheeses.keep_if { |c| c}
=end
| true |
85f0e6070d795953710b3d2a7c40c4eb2ef563b2
|
Ruby
|
nminhthien/LogivanTest
|
/lib/product.rb
|
UTF-8
| 294 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
require 'error'
module LogivanTest
class Product
attr_accessor :code, :name, :price
def initialize(params = {})
raise Error::PARAMS_MUST_BE_HASH unless params.is_a? Hash
@code = params[:code]
@name = params[:name]
@price = params[:price]
end
end
end
| true |
ff63de6eba9ffe09b0bc1341b970f1483a7b96e0
|
Ruby
|
spikesp/Ex_programming_foundation
|
/lesson_3/hard_4.rb
|
UTF-8
| 290 | 2.9375 | 3 |
[] |
no_license
|
def generate_uuid
arr = ('a'..'z').to_a + ('0'..'9').to_a
uuid = ''
sections = [8, 4, 4, 4, 12]
sections.each_with_index do |section, index|
section.times { uuid += arr.sample}
if index < 4
uuid += '-'
else
break
end
end
uuid
end
p generate_uuid
| true |
4bf963dc1d1f292bf483d32459009f05eef92730
|
Ruby
|
harunawaizumi/lean_to_code_with_ruby
|
/239_Class_Variables_and_Instance_Variables.rb
|
UTF-8
| 521 | 3.390625 | 3 |
[] |
no_license
|
class Pay
@@shared_count = 0 # sigil: class variables
@@maker = "LINE"
# a process runs whenever a new instance is instantiated.
def initialize
@count = 0
@@shared_count += 1
end
def pay
@count += 1
end
def self.shared_count # class methods are prefixed with self keyword.
@@shared_count += 1
end
def maker
"#{@@maker} is producing"
end
end
p Pay.shared_count
p1 = Pay.new
p1.pay
p2 = Pay.new
p2.pay
p3 = Pay.new
p3.pay
p Pay.shared_count
puts p1.pay
puts p2.pay
puts p3.pay
| true |
1221706206356768e6673d53c030b4e26b094bfb
|
Ruby
|
russenoire/ls100
|
/ruby_basics/hashes/low_med_high.rb
|
UTF-8
| 110 | 2.875 | 3 |
[] |
no_license
|
numbers = {
high: 100,
medium: 50,
low: 10
}
low_numbers = numbers.select {|k,v| v < 25}
p low_numbers
| true |
6cf33d5e64890813366740931a18241d8817211b
|
Ruby
|
jaishanker/dbp
|
/copy/lib/.svn/text-base/sitemap.rb.svn-base
|
UTF-8
| 8,314 | 2.671875 | 3 |
[] |
no_license
|
class Sitemap
require 'fastercsv'
require 'design.rb'
require 'rubygems'
require 'fileutils'
require 'builder'
require 'logger'
require 'csv'
require 'uri'
@log = Logger.new(File.open('log/sitemap.log','a'))
# This method creates the script that will generate the sitemap xmls for cleartrip
def self.generate_sitemap(static = "")
log "-------------------Start-------------------"
#create output directory if doesnt exist !
self.create_output_dir()
# delete previous content from output directory
if CLEARTRIP["DELETE_OP_DIR_CONTENT"] == "Y"
log "Deleting old xml files.."
Dir[CLEARTRIP["OUTPUT_DIR"] + "*.xml"].each do |file_name|
File.delete(file_name)
end
end
# copy static file into sitemap directory
unless static == ""
begin
FileUtils.cp static, CLEARTRIP["OUTPUT_DIR"] + CLEARTRIP["STATIC_FILE_NAME"]
log "Static xml file #{static} copied into output directory."
rescue
log "Wrong static xml file path provided."
end
else
log "No Static xml file path provided."
end
# generate xml for designs
generate_design_xmls()
# generate xml for learning
generate_learning_xmls
# generate xml for learning
generate_game_xmls
# generate xml for learning
generate_news_xmls
#generates site index file with all the xml urls in it
generate_sitemap_index()
end
def self.create_output_dir()
unless File.directory?(CLEARTRIP["OUTPUT_DIR"])
curr = "/"
CLEARTRIP["OUTPUT_DIR"].split('/').each do |dir|
unless File.directory?(curr + dir)
FileUtils.mkdir(curr + dir)
log "Created directory : " + curr + dir
end
curr << dir << "/"
end
log "Output Directory created successful."
end
end
def self.generate_design_xmls
log "Fetching designs info :"
# hotels = Net::HTTP.get(URI.parse(CLEARTRIP["STATION_CSV_URL"]))
designs = Design.find_all_active_for_xml
log "generating design xmls :"
i = 1
file_count = 1
loc = []
designs.each_with_index do |design,index|
loc << escape(CLEARTRIP["SITE_URL"] + 'designs/design/'+ design.permalink)
i = i + 1
if i >= CLEARTRIP["XML_NODE_LIMIT"] or index == (designs.size - 1)
xm = Builder::XmlMarkup.new(:indent => 2 )
xm.instruct!
xm.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | us |
loc.each do |url|
us.url do |u|
u.loc(url)
end
end
end
f= File.new(CLEARTRIP["OUTPUT_DIR"] + "designs-#{file_count.to_s}.xml",'w')
f << xm.target!
f.close
log "Created designs-#{file_count.to_s}.xml file with #{i.to_s} nodes."
# clearing the variables
loc = []
file_count += 1
i = 1
end
end # design.each
# log "Total " + hotels.length.to_s + " hotels."
# log "Total " + file_count.to_s + " stations xmls."
# log "Deleting temp files.."
# File.delete( CLEARTRIP["OUTPUT_DIR"] + 'stations.txt')
log "Done."
end
def self.generate_learning_xmls
log "Fetching learnings info :"
# hotels = Net::HTTP.get(URI.parse(CLEARTRIP["STATION_CSV_URL"]))
learnings = Learning.find_all_active_for_xml
log "generating learning xmls :"
i = 1
file_count = 1
loc = []
learnings.each_with_index do |learning,index|
loc << escape(CLEARTRIP["SITE_URL"] + 'learnings/learning/'+ learning.permalink)
i = i + 1
if i >= CLEARTRIP["XML_NODE_LIMIT"] or index == (learnings.size - 1)
xm = Builder::XmlMarkup.new(:indent => 2 )
xm.instruct!
xm.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | us |
loc.each do |url|
us.url do |u|
u.loc(url)
end
end
end
f= File.new(CLEARTRIP["OUTPUT_DIR"] + "learnings-#{file_count.to_s}.xml",'w')
f << xm.target!
f.close
log "Created learnings-#{file_count.to_s}.xml file with #{i.to_s} nodes."
# clearing the variables
loc = []
file_count += 1
i = 1
end
end # design.each
# log "Total " + hotels.length.to_s + " hotels."
# log "Total " + file_count.to_s + " stations xmls."
# log "Deleting temp files.."
# File.delete( CLEARTRIP["OUTPUT_DIR"] + 'stations.txt')
log "Done."
end
def self.generate_game_xmls
log "Fetching game info :"
# hotels = Net::HTTP.get(URI.parse(CLEARTRIP["STATION_CSV_URL"]))
games = Game.find_all_active_for_xml
log "generating game xmls :"
i = 1
file_count = 1
loc = []
games.each_with_index do |game,index|
loc << escape(CLEARTRIP["SITE_URL"] + 'games/game/'+ game.permalink)
i = i + 1
if i >= CLEARTRIP["XML_NODE_LIMIT"] or index == (games.size - 1)
xm = Builder::XmlMarkup.new(:indent => 2 )
xm.instruct!
xm.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | us |
loc.each do |url|
us.url do |u|
u.loc(url)
end
end
end
f= File.new(CLEARTRIP["OUTPUT_DIR"] + "games-#{file_count.to_s}.xml",'w')
f << xm.target!
f.close
log "Created games-#{file_count.to_s}.xml file with #{i.to_s} nodes."
# clearing the variables
loc = []
file_count += 1
i = 1
end
end # design.each
# log "Total " + hotels.length.to_s + " hotels."
# log "Total " + file_count.to_s + " stations xmls."
# log "Deleting temp files.."
# File.delete( CLEARTRIP["OUTPUT_DIR"] + 'stations.txt')
log "Done."
end
def self.generate_news_xmls
log "Fetching news info :"
# hotels = Net::HTTP.get(URI.parse(CLEARTRIP["STATION_CSV_URL"]))
news = News.find_all_active_for_xml
log "generating news xmls :"
i = 1
file_count = 1
loc = []
news.each_with_index do |new,index|
loc << escape(CLEARTRIP["SITE_URL"] + 'news/news/'+ new.permalink)
i = i + 1
if i >= CLEARTRIP["XML_NODE_LIMIT"] or index == (news.size - 1)
xm = Builder::XmlMarkup.new(:indent => 2 )
xm.instruct!
xm.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | us |
loc.each do |url|
us.url do |u|
u.loc(url)
end
end
end
f= File.new(CLEARTRIP["OUTPUT_DIR"] + "news-#{file_count.to_s}.xml",'w')
f << xm.target!
f.close
log "Created news-#{file_count.to_s}.xml file with #{i.to_s} nodes."
# clearing the variables
loc = []
file_count += 1
i = 1
end
end # design.each
# log "Total " + hotels.length.to_s + " hotels."
# log "Total " + file_count.to_s + " stations xmls."
# log "Deleting temp files.."
# File.delete( CLEARTRIP["OUTPUT_DIR"] + 'stations.txt')
log "Done."
end
def self.escape(url)
URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
url
end
def self.generate_sitemap_index
dir = Dir[CLEARTRIP["OUTPUT_DIR"] + "/*.xml"]
log "creating sitemap index :"
xm = Builder::XmlMarkup.new(:indent => 2 )
xm.instruct!
xm.sitemapindex(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | si |
dir.each do |filename|
si.sitemap do |s|
s.loc((CLEARTRIP["OUTPUT_URL"] + filename.split('/').last))
s.lastmod(File.open(filename,'r').mtime.to_date.to_s)
end
end
end
# delete old sitemap index if already exists
log "deleting old sitemap file if exists.."
of = File.delete(CLEARTRIP["OUTPUT_DIR"] + "sitemap.xml") if File.exist?(CLEARTRIP["OUTPUT_DIR"] + "sitemap.xml")
f= File.new(CLEARTRIP["OUTPUT_DIR"] + "sitemap.xml",'w')
f << xm.target!
f.close
log "Sitemap index created successfully."
log "-------------------Done--------------------\n"
end
def self.log(message)
message = Time.now.to_s(:db) + " : " + message
@log.debug message
puts message
end
end
| true |
92b3ad33774ff327d9137b181e724bcb26bf0112
|
Ruby
|
marinaflores/book-App
|
/app/controllers/home_controller.rb
|
UTF-8
| 906 | 2.625 | 3 |
[] |
no_license
|
class HomeController < ApplicationController
before_action :authenticate_user!
def index
@weekdays = ["Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira"]
@timetables = ["8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"]
if params[:new_day].present? && ! params[:new_day].blank?
@today = params[:new_day].to_date
else
@today = Time.current.strftime('%d/%m/%Y').to_date
end
if @today.monday? || @today.sunday? || @today.saturday?
add = 0
elsif @today.tuesday?
add = 1
elsif @today.wednesday?
add = 2
elsif @today.thursday?
add = 3
elsif @today.friday?
add = 4
end
@dateIni = (@today - add.days)
@dates = []
dd = 0
@weekdays.each do |_day|
@dates << (@dateIni + dd.days).strftime('%d/%m/%Y')
dd += 1
end
end
end
| true |
74fee1cfdcaefdd808f7cc44791ec401366943c4
|
Ruby
|
beliar91/house_hold_chores
|
/app/models/task.rb
|
UTF-8
| 720 | 2.78125 | 3 |
[] |
no_license
|
class Task < ActiveRecord::Base
#validations:
validates :name, presence: true, uniqueness: true
validates :completion_time, presence: true
#scopes:
scope :by_status, -> (status) {where(complete: status)}
scope :completed, -> {where complete: true}
scope :pending, -> {where complete: false}
#associations:
belongs_to :house_hold
def self.count_average_execution_time(status)
sum_of_tasks_by_status = Task.by_status(status).inject(0) {|sum, task| sum += task.completion_time }
number_of_tasks = Task.by_status(status).count
average = sum_of_tasks_by_status / number_of_tasks
p "Average execution time for tasks with status: #{status} is " << average.to_s
average
end
end
| true |
118ebea8c9bf41d9a1312f4b86320097f4d4c6fd
|
Ruby
|
danielacodes/ruby-exercises
|
/arrays/a_ex3.rb
|
UTF-8
| 146 | 3.8125 | 4 |
[] |
no_license
|
# Write a Ruby program to pick number
# of random elements from an given array.
array = [12,24,56,41]
puts array.sample(2)
puts array.sample(3)
| true |
6aeb4c15a1c8deaec728693444b1209793c37b2c
|
Ruby
|
aaltowebapps/team-7
|
/server/building.rb
|
UTF-8
| 1,805 | 2.90625 | 3 |
[] |
no_license
|
require_relative 'building_classes.rb'
#
# building.rb
#
# Contains logic for accessing building and floormap data.
#
# Returns all building data in JSON format (see wiki, TODO: URL).
def building_data(timestamp = nil)
# TODO: replace temporary static test data with live data read from DB
data_file = 'building_data.json'
contents = File.open(data_file, 'rb').read
data = JSON.parse(contents)
if data['last_updated'] == nil
data['last_updated'] = File.mtime(data_file).iso8601
end
if (timestamp == nil || Time.parse(data['last_updated']) > timestamp)
return JSON.pretty_generate(data)
else
return ''
end
end
# Returns available floormap names. If timestamp is given, only files newer
# than the given time are returned.
def floormap_names(timestamp = nil)
names = []
basenames = Dir.entries(FLOORMAP_DIR)
basenames.each do |basename|
filename = File.join(FLOORMAP_DIR, basename)
if File.file?(filename) && (timestamp == nil || File.mtime(filename) > timestamp)
names << basename
end
end
names
end
# mappings between file endings & mime types. contains only those which aren't the same
MIME_TYPE_FOR_ENDING = {"svg" => "image/svg+xml"}
# Returns structural floormap data (binary content + metadata) for the given id.
def floormap_data(id)
contents = File.open(File.join(FLOORMAP_DIR, id), 'rb').read
fileinfo = Hash.new
fileinfo['id'] = id
fileinfo['contents'] = Base64.encode64(contents)
ending = id.split('.')[-1]
fileinfo['type'] = MIME_TYPE_FOR_ENDING[ending] || ('image/' + ending)
fileinfo
end
# Returns an array of floormap data structures for the given floormap names.
def floormap_data_collection(names)
floormaps = []
names.each do |name|
floormaps << floormap_data(name)
end
floormaps
end
| true |
4033ce87a28bcbe20918a0e06c8620daf6aa27a6
|
Ruby
|
NishantUpadhyay-BTC/demo_one_app
|
/myprograms/lib/ex32.rb
|
UTF-8
| 822 | 4.25 | 4 |
[] |
no_license
|
the_count = [1,2,3,4,5]
fruits = ['apple','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
#this first kind of fo-loop goes through an array
the_count.each do |number|
puts "This is count #{number}"
end
#same as above, but using a block instead
for fruit in fruits
puts "A fruit of type : #{fruit}"
end
#also we can go through amixed arrays too
for i in change
puts "I got #{i}"
end
#we can also build arrays, first start with an empty
elements = Array.new # also created as elements = [] both are equal
#then use a range object to do 0 to 5 counts
for i in (0...5)#count 0 to 4 if .. dots then count 0 to 5
puts "Adding #{i} to the list."
#push is a function that arrays understand
elements << i
end
#now we can put them out too
for i in elements
puts "Elements was: #{i}"
end
| true |
ff3e1eec28a6eb1f9454c2a8e9bf90163dd801ef
|
Ruby
|
pratamashooter/RubyBasic
|
/RubyFile/RubyFile/latihan_ruby_24.rb
|
UTF-8
| 118 | 3.21875 | 3 |
[] |
no_license
|
# Return Method
def halo
"Saya sedang belajar Ruby"
end
def diBalik
halo.reverse
end
puts halo
puts diBalik
| true |
c2d6c08e768d1c859b449658accf7de433c031dd
|
Ruby
|
AustenGG/notes
|
/notes_app/lib/app.rb
|
UTF-8
| 313 | 2.953125 | 3 |
[] |
no_license
|
class Notes
def initialize
@notes = {}
end
def add_note(title, body)
@notes[title] = body
"Your note has been saved!"
end
def print_titles
return @notes.keys
end
def print_notebook
return @notes
end
def view_titles(title)
return @notes[title]
end
end
| true |
b226148d187dc74fc44f7bc399b1f0c079a1d507
|
Ruby
|
jdkaplan/advent-of-code
|
/2019/day11/part1.rb
|
UTF-8
| 2,378 | 3.75 | 4 |
[] |
no_license
|
# frozen_string_literal: true
require 'set'
require_relative 'intcode'
Point = Struct.new(:x, :y) do
def to_s
"(#{x}, #{y})"
end
end
class Hull
def initialize
@panels = Hash.new { |hash, key| hash[key] = :black }
@painted = Set.new
end
def color_at(point)
@panels[point]
end
def paint(point, color)
@painted << point
@panels[point] = color
end
def painted
@painted.count
end
end
class DoneExecuting < StandardError; end
class Robot
def initialize(program, hull)
@computer = Intcode::Computer.new(program.as_memory) { on_input }
@hull = hull
@facing = :up
@position = Point.new(0, 0)
end
def step
color_output = nil
direction_output = nil
color_output = tick until color_output
direction_output = tick until direction_output
@hull.paint(@position, color(color_output))
@facing = turn(@facing, direction_output)
@position = move(@position, @facing)
end
def tick
ret = @computer.tick
raise DoneExecuting if ret == :done_executing
ret
end
def on_input
color = @hull.color_at(@position)
case color
when :black
0
when :white
1
else
raise ArgumentError, "unexpected color: #{color}"
end
end
def color(code)
case code
when 0
:black
when 1
:white
else
raise ArgumentError, "unexpected color code: #{code}"
end
end
DIRECTIONS = %i[up right down left].freeze
def turn(facing, direction_code)
idx = DIRECTIONS.index(facing)
case direction_code
when 0
# left 90 degrees (ccw)
next_idx = (idx - 1) % DIRECTIONS.length
when 1
# right 90 degrees (cw)
next_idx = (idx + 1) % DIRECTIONS.length
else
raise ArgumentError, "unexpected direction code: #{direction_code}"
end
DIRECTIONS.fetch(next_idx)
end
def move(pos, direction)
case direction
when :up
Point.new(pos.x, pos.y - 1)
when :down
Point.new(pos.x, pos.y + 1)
when :left
Point.new(pos.x - 1, pos.y)
when :right
Point.new(pos.x + 1, pos.y)
else
raise ArgumentError, "unexpected direction: #{direction}"
end
end
end
program = Intcode.read(File.join(__dir__, 'input'))
hull = Hull.new
robot = Robot.new(program, hull)
loop do
robot.step
rescue DoneExecuting
break
end
puts hull.painted
| true |
ff749649f1511e83808ba97a140447af06579567
|
Ruby
|
AlexHandy1/MA_week2_battleships_new
|
/lib/Board.rb
|
UTF-8
| 2,486 | 3.59375 | 4 |
[] |
no_license
|
require_relative 'ship'
require_relative 'destroyer'
require_relative 'cruiser'
require_relative 'battleship'
require_relative 'submarine'
require_relative 'carrier'
class Board
attr_accessor :grid, :guesses, :fleet, :ship_positions, :game_over
def initialize(size = 10)
@grid = Array.new(size){Array.new(size)}
@fleet = []
@guesses = []
@game_over = false
end
def place ship
row, col = convertor(ship.position)
fail 'Out of bounds' if out_of_bounds?(row, col)
fail "Already a ship" if grid[row][col].nil? == false
if ship.direction == "V"
for x in 0..ship.size-1
if row+x > 9 || col > 9
grid[row+x-1][col] = nil
fail 'Out of bounds'
end
if grid[row+x][col].nil? == false
grid[row+x-1][col] = nil
fail 'Already a ship'
end
grid[row+x][col] = ship
end
@fleet << ship
else
for x in 0..ship.size-1
if row > 9 || col+x > 9
grid[row][col+x-1] = nil
fail 'Out of bounds'
end
if grid[row][col+x].nil? == false
grid[row][col+x-1] = nil
fail 'Already a ship'
end
grid[row][col+x] = ship
end
@fleet << ship
end
end
def check_grid square
row, col = convertor(square)
grid[row][col]
end
def fire square
row, col = convertor(square)
if grid[row][col] == nil
grid[row][col] = "X"
elsif grid[row][col].nil? == false && grid[row][col] != "X" && grid[row][col] != "HIT"
fleet.each do |ship|
if ship == grid[row][col]
grid[row][col].is_hit
grid[row][col] = "HIT"
ship.is_sunk
game_over
end
end
else
fail "Already guessed"
end
end
def convertor square
alphabet = ("a".."z").to_a
row, col = square.downcase.split(//,2)
coords = alphabet.index(row), (col.to_i) - 1
end
def show_grid
grid.each { |x| p x }
end
def out_of_bounds?(row, col)
row > 9 || col > 9
end
def game_over #refactored >> reduced extra puts each hit and added .all? parameter
if fleet.all?{|ship| ship.sunk?}
game_over = true
puts "You win!"
end
return game_over #add exit program
end
#added clear_board to start new game
def clear_board
grid.map!{|a,b,c,d,e,f,g,h,i,j| a,b,c,d,e,f,g,h,i,j = nil, nil, nil, nil,nil, nil, nil, nil, nil, nil }
#would also need to empty fleet
end
end
| true |
d21a6605c2e2705568414ddf90140df34993e052
|
Ruby
|
Alex1100/RailsCodingChallenge-master
|
/spec/cuboid_spec.rb
|
UTF-8
| 6,283 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
require_relative '../lib/cuboid'
#This test is incomplete and, in fact, won't even run without errors.
# Do whatever you need to do to make it work and please add your own test cases for as many
# methods as you feel need coverage
describe Cuboid do
describe "vertices" do
it "finds all vertices (aka edges)" do
init_args = [[0, 0, 0], 4, 10, 4]
subject = Cuboid.new(*init_args)
expect(subject.vertices.class).to eq Array
expect(subject.vertices[0][0][0].class).to eq String
expect(subject.vertices).to eq [["ftl", [0, 0, 0]], ["ftr", [10, 0, 0]], ["fbl", [0, -4, 0]], ["fbr", [10, -4, 0]], ["retl", [0, 0, -4]], ["retr", [10, 0, -4]], ["rebl", [0, -4, -4]], ["rebr", [10, -4, -4]]]
end
end
describe "move_to" do
it "changes the origin in the simple happy case" do
init_args = [[0,0,0], 4, 10, 4]
subject = Cuboid.new(*init_args)
move_args = [1, 2, 3.5]
subject = subject.move_to!(*move_args)
expect(subject.origin.class).to eq Array
expect(subject.origin[0].class).to eq Integer || Float
expect(subject.origin).not_to eq [100, 100, 10]
expect(subject.origin).to eq move_args
expect(subject.vertices.class).to eq Array
expect(subject.vertices[0][0][0].class).to eq String
expect(subject.vertices).to eq [["ftl", [1, 2, 3.5]], ["ftr", [11, 2, 3.5]], ["fbl", [1, -2, 3.5]], ["fbr", [11, -2, 3.5]], ["retl", [1, 2, -0.5]], ["retr", [11, 2, -0.5]], ["rebl", [1, -2, -0.5]], ["rebr", [11, -2, -0.5]]]
end
it "changes the origin in the simple happy case with higher input values" do
init_args = [[0,0,0], 4, 10, 4]
subject = Cuboid.new(*init_args)
move_args = [100, 200, 300.5]
subject = subject.move_to!(*move_args)
expect(subject.origin.class).to eq Array
expect(subject.origin[0].class).to eq Integer || Float
expect(subject.origin).not_to eq [100, 100, 10]
expect(subject.origin).to eq move_args
expect(subject.vertices.class).to eq Array
expect(subject.vertices[0][0][0].class).to eq String
expect(subject.vertices).to eq [["ftl", [100, 200, 300.5]], ["ftr", [110, 200, 300.5]], ["fbl", [100, 196, 300.5]], ["fbr", [110, 196, 300.5]], ["retl", [100, 200, 296.5]], ["retr", [110, 200, 296.5]], ["rebl", [100, 196, 296.5]], ["rebr", [110, 196, 296.5]]]
end
end
describe "horizontal_intersection?" do
it "returns false if there aren't shared points along the x-axis of a 3D space between two objects" do
args = [[0, 0, 0], 2, 4, 2]
test_subject_args = [[5, 3, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.horizontal_intersection?(test_subject)).to eq false
end
it "returns true if there are shared points along the x-axis of a 3D space between two objects" do
args = [[0, 0, 0], 2, 4, 2]
test_subject_args = [[4, 3, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.horizontal_intersection?(test_subject)).to eq true
end
end
describe "vertical_intersection?" do
it "returns false if there aren't shared points along the y-axis of a 3D space between two objects" do
args = [[0, 0, 0], 4, 4, 2]
test_subject_args = [[5, 10, 10], 30, 50, 30]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.vertical_intersection?(test_subject)).to eq false
end
it "returns true if there are shared points along the y-axis of a 3D space between two objects" do
args = [[0, 0, 0], 4, 4, 2]
test_subject_args = [[5, 3, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.vertical_intersection?(test_subject)).to eq true
end
end
describe "within_z_index_range?" do
it "returns false if there aren't shared points along the z-axis of a 3D space between two objects" do
args = [[0, 0, 0], 4, 6.5, 4]
test_subject_args = [[10, 30, -100], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.within_z_index_range?(test_subject)).to eq false
end
it "returns true if there are shared points along the z-axis of a 3D space between two objects" do
args = [[0, 0, 0], 4, 4, 2]
test_subject_args = [[5, 3, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.within_z_index_range?(test_subject)).to eq true
end
end
describe "intersects?" do
it "returns false if intersections between objects aren't found" do
args = [[0, 0, 0], 2, 4, 2]
test_subject_args = [[5, 3, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.intersects?(test_subject)).to eq !!original_subject.intersects?(test_subject)
expect(original_subject.intersects?(test_subject)).to eq false
end
it "returns true if intersections between objects are found" do
args = [[0, 0, 0], 2, 4, 2]
test_subject_args = [[4, 2, 0], 3, 5, 3]
original_subject = Cuboid.new(*args)
test_subject = Cuboid.new(*test_subject_args)
expect(original_subject.intersects?(test_subject)).to eq !!original_subject.intersects?(test_subject)
expect(original_subject.intersects?(test_subject)).to eq true
end
end
describe "rotate" do
it "rotates an object 90º counter-clockwise" do
args = [[1, 2, 2], 2, 4, 2]
subject = Cuboid.new(*args)
new_subject = subject.rotate(false)
expect(subject.origin[1]).to eq (new_subject.origin[0] * -1)
expect(new_subject.vertices).not_to eq subject.vertices
end
it "rotates an object 90º clockwise" do
args = [[1, 2, 2], 2, 4, 2]
subject = Cuboid.new(*args)
new_subject = subject.rotate(true)
expect(subject.origin[0]).to eq (new_subject.origin[1] * -1)
expect(new_subject.vertices).not_to eq subject.vertices
end
end
end
| true |
d2470c361b7196ebe351da4601f7b6d16c03af45
|
Ruby
|
germanescobar/articles
|
/test/models/article_test.rb
|
UTF-8
| 653 | 2.734375 | 3 |
[] |
no_license
|
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
test "article is not created without a title" do
article = Article.new
assert_not article.save, "article should not be created without a title"
end
test ".word_count returns the correct number of words" do
article = Article.new(title: "Art 1", body: "Hola Mundo. Esto es una prueba!", published: true)
assert_equal 6, article.word_count
end
test "published scope only returns published articles" do
articles = Article.published
assert_equal 1, articles.length
article = articles(:published)
assert_equal article.id, articles[0].id
end
end
| true |
935b10d1c88956a8efff46638b985edf73639a0a
|
Ruby
|
ivanvc/pft
|
/spec/base_spec.rb
|
UTF-8
| 1,755 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require File.dirname(__FILE__) + '/../lib/pft.rb'
describe "Pft::Base" do
it "should raise an error with no arguments" do
lambda { Pft::Base.tweet.should_not }.should raise_error("Please provide a message")
end
it "should respond with the version" do
Pft::Base.version
end
it "should open not default configuration file" do
File.stub!(:open).and_return(["token=test"])
Pft::Base.options("blah")[:token].should eql("test")
end
end
describe "Pft::Base instance" do
before(:each) do
@pft = Pft::Base.new
end
it "should have a oauth client" do
@pft.oauth.should_not be_nil
end
describe "handling no such user error" do
it "should raise it if the user is invalid when posting a reply" do
lambda { @pft.reply_to('123123wjas8duas8d', 'blah') }.should raise_error("User or last tweet not found")
end
it "should raise it if the user is invalid when posting a direct message" do
lambda { @pft.direct_message('123123wjas8duas8d', 'blah') }.should raise_error("User or last tweet not found")
end
it "should raise it if the user is invalid when posting a retweet" do
lambda { @pft.retweet('123123wjas8duas8d') }.should raise_error("User or last tweet not found")
end
end
it "should print confirmation message" do
@pft.message_for('test').should == "pft! successfully sent a test"
end
it "should print confirmation message with an user" do
@pft.message_for('test', 'testo').should == "pft! successfully sent a test to testo"
end
it "should handle urls" do
original_text = "testing http://www.example.com/blaaaaaaaaaaaaaaaaaaaaaaaah a"
@pft.parse_urls(original_text).should_not == original_text
end
end
| true |
f31b456f2ff0b56596fa4cc42af9b9cd470ee013
|
Ruby
|
marksingh910/launchschool
|
/prep_course/ruby_book_exercises/exercises/exercises_15.rb
|
UTF-8
| 449 | 3.546875 | 4 |
[] |
no_license
|
hash1 = {shoes: "nike",
"hat" => "adidas",
:hoodie => true}
hash2 = {"hat" => "adidas",
:shoes => "nike",
hoodie: true}
if hash1 == hash2
puts "These hashes are the same!"
else
puts "These hashes are not the same!"
end
# I thought it would say they are not the same. This is false. Hash orders don't matter because you use the key as a reference. Both syntaxes old and new
# can be used as well.
| true |
3ea702cc0841a9bad1da83ba3dc77ae0075f8e42
|
Ruby
|
Ma9sha/chitter-challenge
|
/spec/chitter_spec.rb
|
UTF-8
| 551 | 2.921875 | 3 |
[] |
no_license
|
describe '.all' do
it 'returns names and message of chitters' do
posts = Peeps.all
expect(posts[0].name).to eq "manisha"
end
end
describe '.add name' do
it 'stores the name of blogger' do
posts = Peeps.all
allow(posts).to receive(:add_name).and_return(4)
expect(posts.add_name).to eq(4)
end
end
describe '.add message' do
it 'stores the message of the blogger in message table' do
posts1 = Peeps.all
Peeps.add_message("Hello", 5)
posts2 = Peeps.all
expect(posts1.length).to eq(posts2.length-1)
end
end
| true |
73840d48184b51695d060af365a731237f79a4bf
|
Ruby
|
ducktyper/ora-cli
|
/lib/ora/cli/tasks/switch_branch.rb
|
UTF-8
| 1,021 | 2.53125 | 3 |
[] |
no_license
|
require 'ora/cli/task'
require 'ora/cli/precondition_error'
module Ora::Cli
class SwitchBranch < Task
attr_reader :target_branch
def commands
'
:only_feature_branch_can_be_dirty!
:switch_to
git stash save -u "OraCli"
git checkout #{target_branch}
:apply_stash
'
end
private
def only_feature_branch_can_be_dirty!
if main_branch? && dirty?
raise PreconditionError, "#{branch} branch can't be dirty."
end
''
end
def switch_to
@target_branch = stdin.select("git branch | grep '^ ' | sed 's/^ //'")
''
end
def apply_stash
return '' if target_stash_revision.empty?
"git stash pop #{target_stash_revision}"
end
def target_stash_revision
@target_stash_revision ||=
@bash.silent("git stash list | grep '#{target_stash_name}' | sed s/:.*//").
split("\n").first.to_s.strip
end
def target_stash_name
"On #{target_branch}: OraCli"
end
end
end
| true |
036372e74db16f6b4aea77eed84ec4dbaa3187ed
|
Ruby
|
fatcatdog/W1D5
|
/tic_tac_toe/skeleton/lib/tic_tac_toe_node.rb
|
UTF-8
| 747 | 3.171875 | 3 |
[] |
no_license
|
require_relative 'tic_tac_toe'
class TicTacToeNode
attr_accessor :board, :next_mover_mark, :prev_move_pos
def initialize(board, next_mover_mark, prev_move_pos = nil)
@board = board
@next_mover_mark = next_mover_mark
@prev_move_pos = prev_move_pos unless prev_move_pos == nil
end
def losing_node?(evaluator)
end
def winning_node?(evaluator)
end
# This method generates an array of all moves that can be made after
# the current move.
def children
results = []
@board.each do |y|
@row.each do |x|
if @board[y][x].nil?
dupe_board = @board.dup
dupe_board([x,y], @next_mover_mark)
result << dupe_board
end
end
end
results
end
end
| true |
2ed4ddcfd54931a796bf66c8097379b297b75715
|
Ruby
|
knaveofdiamonds/conspirator
|
/spec/data_encoding_spec.rb
|
UTF-8
| 1,219 | 2.78125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Google Charts' extended data encoding" do
it "should translate an integer to two characters" do
ExtendedEncoding.new.translate(0).should == "AA"
ExtendedEncoding.new.translate(25).should == "AZ"
ExtendedEncoding.new.translate(26).should == "Aa"
ExtendedEncoding.new.translate(62).should == "A-"
ExtendedEncoding.new.translate(63).should == "A."
ExtendedEncoding.new.translate(4095).should == ".."
end
it "should translate out of bounds numbers to '__'" do
ExtendedEncoding.new.translate(4096).should == "__"
ExtendedEncoding.new.translate(-1).should == "__"
end
it "should translate nil numbers to '__'" do
ExtendedEncoding.new.translate(nil).should == "__"
end
it "should truncate floating point numbers to integers before encoding" do
ExtendedEncoding.new.translate(1.1).should == "AB"
ExtendedEncoding.new.translate(1.9).should == "AB"
end
it "should apply a translation to every number in an array" do
ExtendedEncoding.new.encode([0,1,4095]).should == "e:AAAB.."
end
it "should have a maximum value of 4095" do
ExtendedEncoding::MAX.should == 4095
end
end
| true |
7ce3a99aa1215684bd388a4f943f8d0252ddf3f6
|
Ruby
|
zapidan/ruby-playground
|
/3-reducing-costs-with-duck-typing/preparer_duck_type.rb
|
UTF-8
| 950 | 3.375 | 3 |
[] |
no_license
|
# Trip preparation is easier with a preparer duck type
class Trip
attr_reader :bicycles, :customers, :vehicle
def prepare(preparers)
preparers.each { |preparer| preparer.prepare_trip(self) }
end
end
# Preparer is a duck that responds to prepare_trip
# Flexible extension, a new preparer can be added in the future
# so long as it implements the prepare_trip method
class Mechanic
def prepare_trip(trip)
this.bicycles.each { |bicycle| prepare_bicycle(bicycle) }
end
protected
def prepare_bicycle(bicycle)
# ...
end
end
class TripCoordinator
def prepare_trip(trip)
this.customers.each { |customer| buy_food(trip.customers) }
end
protected
def buy_food(customers)
# ...
end
end
class Driver
def prepare_trip(trip)
vehicle = trip.vechicle
gas_up(vehicle)
fill_water_tank(vehicle)
end
protected
def gas_up(vehicle)
# ...
end
def fill_water_tank(vehicle)
# ...
end
end
| true |
b48f83638c37fea1f85ef8209342fdbfd0b2e51d
|
Ruby
|
pathways2050/excel_to_code
|
/spec/compile/ruby/check_for_unknown_functions_spec.rb
|
UTF-8
| 478 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require_relative '../../spec_helper'
describe CheckForUnknownFunctions do
it "should print a list of formulae that are in the input but have not been implemented by the compiler" do
input = <<END
A1\t[:function, "AVERAGE", [:number, "1"]]
A2\t[:function, "NOT IMPLEMENTED FORMULA", [:number, "1"]]
END
expected = <<END
NOT IMPLEMENTED FORMULA
END
i = StringIO.new(input)
o = StringIO.new
c = CheckForUnknownFunctions.new
c.check(i,o)
o.string.should == expected
end
end
| true |
67d32da8980d71a575cb28bb8e3cfc31d8565417
|
Ruby
|
sumajirou/ProjectEuler
|
/p060 copy.rb
|
UTF-8
| 494 | 3.375 | 3 |
[] |
no_license
|
require 'prime'
# 問題の確認
[3,7,109,673].permutation(2).map{|n,m| (n.to_s+m.to_s).to_i}.all?(&:prime?)
def check(primes)
primes.permutation(2) do |n,m|
unless (n * 10 ** Math.log10(m).ceil + m).prime?
return false
end
end
return true
end
26.upto(1000) do |sum|
end
sum = 26
prime_1000 = Prime.each(1000).to_a.drop(1)
prime_1000.combination(3) do |primes|
if check(primes)
p [primes.sum,primes]
end
end
| true |
37bd42f3497ca4c5b0897f3515d59b7b089c8525
|
Ruby
|
RubyCamp/rc2011s_g1
|
/dice_game/map.rb
|
UTF-8
| 189 | 2.90625 | 3 |
[] |
no_license
|
# Mapクラスの定義
class Map
def initialize
@x, @y = 0, 0
@map_img = Image.load("Map_image/map.png")
end
def draw
Window.draw(@x, @y, @map_img)
end
end
| true |
c1f53c928e9342d349bdd2f2490273ee1ec291cb
|
Ruby
|
M4r14nn4/Ruby-Bottom-up
|
/numbers/roman_helper.rb
|
UTF-8
| 2,173 | 4.1875 | 4 |
[] |
no_license
|
# created for visualising which logical steps can easily lead to the 'short' solution of representing integers as 'old-school'
# roman nums. Written to show the logic only...
def roman_helper(arabic_num)
if arabic_num < 5
puts 'I' * arabic_num
#integers between 5 and 9
elsif arabic_num >= 5 && arabic_num < 10
puts "V#{'I' * (arabic_num%5)}"
#integers between 10 and 49
elsif arabic_num >= 10 && arabic_num < 50
if arabic_num%10 < 5
puts "#{'X' * (arabic_num/10)}#{'I' * (arabic_num%10)}"
else
puts "#{'X' * (arabic_num/10)}V#{'I' * (arabic_num%5)}"
end
#integers between 50 and 99
elsif arabic_num >= 50 && arabic_num < 100
if arabic_num%10 < 5
puts "L#{'X' * ((arabic_num - 50)/10)}#{'I' * (arabic_num%5)}"
else
puts "L#{'X' * ((arabic_num - 50)/10)}V#{'I' * (arabic_num%5)}"
end
#integers between 100 and 499
elsif arabic_num >=100 && arabic_num < 500
if arabic_num%100 < 50
if arabic_num%10 < 5
puts "#{'C' * (arabic_num/100)}#{'X' * ((arabic_num%100)/10)}#{'I' * (arabic_num%5)}"
else
puts "#{'C' * (arabic_num/100)}#{'X' * ((arabic_num%100)/10)}V#{'I' * (arabic_num%5)}"
end
else
if arabic_num%10 < 5
puts "#{'C' * (arabic_num/100)}L#{'X' * (((arabic_num - 50)%100)/10)}#{'I' * (arabic_num%5)}"
else
puts "#{'C' * (arabic_num/100)}L#{'X' * (((arabic_num - 50)%100)/10)}V#{'I' * (arabic_num%5)}"
end
end
#integers between 500 and 999
elsif arabic_num >=500 && arabic_num < 1000
if arabic_num%100 < 50
if arabic_num%10 < 5
puts "D#{'C' * ((arabic_num-500)/100)}#{'X' * ((arabic_num%100)/10)}#{'I' * (arabic_num%5)}"
else
puts "D#{'C' * ((arabic_num-500)/100)}#{'X' * ((arabic_num%100)/10)}V#{'I' * (arabic_num%5)}"
end
else
if arabic_num%10 < 5
puts "D#{'C' * ((arabic_num-500)/100)}L#{'X' * (((arabic_num - 50)%100)/10)}#{'I' * (arabic_num%5)}"
else
puts "D#{'C' * ((arabic_num-500)/100)}L#{'X' * (((arabic_num - 50)%100)/10)}V#{'I' * (arabic_num%5)}"
end
end
end
end
| true |
acb0030a0e3eaf6dce37cf5c2d5bf54292c00956
|
Ruby
|
griffithlab/civic-server
|
/app/models/scoped_event_feed.rb
|
UTF-8
| 933 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
class ScopedEventFeed
attr_reader :root, :event_subjects, :page, :per
def initialize(root_type, root_id, page = 0, per = 20)
@root = root_type.classify.constantize.find(root_id)
@event_subjects = EventHierarchy.new(root).children
@page = page
@per = per
end
def events
if @events
@events
else
@events = Event.includes(:subject, :organization, :originating_user)
.where(subject: event_subjects)
.order('events.created_at desc')
.page(page)
.per(per)
end
end
def comments
if @comments
@comments
else
comment_ids = events.select { |e| e.state_params['comment'].present? }
.map { |e| e.state_params['comment']['id'] }
comments = Comment.includes(user: [:organizations]).where(id: comment_ids)
@comments = comments.each_with_object({}) do |comment, h|
h[comment.id] = comment
end
end
end
end
| true |
ebfed03ccf4712ffcc9c71664f3ad345a5c6f01a
|
Ruby
|
DanielMulitauopele/black_thursday
|
/test/merchant_repository_test.rb
|
UTF-8
| 2,862 | 3.0625 | 3 |
[] |
no_license
|
require_relative 'test_helper'
require_relative '../lib/merchant_repository.rb'
class MerchantRepositoryTest < Minitest::Test
def setup
merchant_1 = Merchant.new(
name: "Bills Tools",
id: "123",
created_at: "2010-12-10",
updated_at: "2011-12-04"
)
merchant_2 = Merchant.new(
name: "Billys Tools",
id: "124",
created_at: "2010-12-10",
updated_at: "2011-12-04"
)
merchant_3 = Merchant.new(
name: "Bilbos Tools",
id: "125",
created_at: "2010-12-10",
updated_at: "2011-12-04"
)
merchants = [merchant_1, merchant_2, merchant_3]
@merchant_repository = MerchantRepository.new(merchants)
end
def test_it_exists
assert_instance_of MerchantRepository, @merchant_repository
end
def test_it_can_hold_merchants
assert_instance_of Array, @merchant_repository.list
end
def test_its_holding_merchants
assert_instance_of Merchant, @merchant_repository.list[0]
assert_instance_of Merchant, @merchant_repository.list[2]
end
def test_it_can_return_merchants_using_all
assert_instance_of Merchant, @merchant_repository.all[0]
assert_instance_of Merchant, @merchant_repository.all[2]
end
def test_it_can_find_by_id
expected = @merchant_repository.list[0]
actual = @merchant_repository.find_by_id(123)
assert_equal expected, actual
end
def test_it_can_find_by_name
expected = @merchant_repository.list[0]
actual = @merchant_repository.find_by_name("Bills Tools")
assert_equal expected, actual
end
def test_it_can_find_all_by_name
expected = 3
actual = @merchant_repository.find_all_by_name("bil").count
assert_equal expected, actual
actual_2 = @merchant_repository.find_all_by_name("BIL").count
assert_equal expected, actual_2
end
def test_find_all_by_name_returns_empty_array_if_no_match
expected = []
actual = @merchant_repository.find_all_by_name("xyz")
assert_equal expected, actual
end
def test_it_can_create_new_id
expected = "126"
actual = @merchant_repository.create_id
assert_equal expected, actual
end
def test_it_create_new_merchant_with_attributes
new_merchant_added = @merchant_repository.create(name: "Bill Nye")
expected = @merchant_repository.list[-1]
actual = new_merchant_added.last
assert_equal expected, actual
end
def test_it_can_update_name
last_merchant = @merchant_repository.list[-1].name
assert_equal "Bilbos Tools", last_merchant
renamed_merchant = @merchant_repository.update(125, name: "Eric LaSalle")
assert_equal "Eric LaSalle", renamed_merchant
end
def test_it_can_delete_merchant
assert_equal @merchant_repository.list[1], @merchant_repository.find_by_name("Billys Tools")
@merchant_repository.delete(124)
assert_nil @merchant_repository.find_by_name("Billys Tools")
end
end
| true |
712766f6bc907168fa6d9d7188d814a3718f3641
|
Ruby
|
steph544/mod-1-whiteboard-challenge-multiples-of-three-and-five-hou01-seng-ft-042020
|
/lib/multiples.rb
|
UTF-8
| 214 | 3.375 | 3 |
[] |
no_license
|
# Enter your procedural solution here!
require 'pry'
def collect_multiples (limit)
(1...limit).to_a.select{|num| num% 3 ==0 || num % 5 ==0}
end
def sum_multiples(limit)
collect_multiples(limit).sum
end
| true |
e38a7ff743c863fdca9257b245631a54e1b83655
|
Ruby
|
jamesgraham320/the-bachelor-todo-web-100817
|
/lib/bachelor.rb
|
UTF-8
| 1,491 | 3.515625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require "pry"
def get_first_name_of_season_winner(data, season)
# code here
data.each do |season_number, contestants|
if season == season_number
contestants.each do |info|
#binding.pry
if info["status"] == "Winner"
# binding.pry
return info["name"].split(" ").first
end
end
end
end
end
def get_contestant_name(data, occupation)
# code here
data.each do |season_number, contestants|
contestants.each do |info|
#binding.pry
if info["occupation"] == occupation
# binding.pry
return info["name"]
end
end
end
end
def count_contestants_by_hometown(data, hometown)
# code here
count = 0
data.each do |season_number, contestants|
contestants.each do |info|
#binding.pry
if info["hometown"] == hometown
# binding.pry
count += 1
end
end
end
count
end
def get_occupation(data, hometown)
# code here
data.each do |season_number, contestants|
contestant = contestants.find {|info| info["hometown"] == hometown}
return contestant["occupation"] if contestant != nil
end
end
def get_average_age_for_season(data, season)
# code here
count = 0.0
total = 0.0
data.each do |season_number, contestants|
if season == season_number
contestants.each do |info|
total = total + info["age"].to_f
count += 1.0
end
end
end
avg = (total/count).round
end
| true |
ddf145cfef5532942d4c41a3fa27ade8e60203a6
|
Ruby
|
victornava/exercises
|
/2016.beautiful-code.rb
|
UTF-8
| 4,424 | 3.96875 | 4 |
[] |
no_license
|
# https://programmingpraxis.com/2009/09/11/beautiful-code/
#
# Beautiful Code
#
# In their book The Practice of Programming, Brian Kernighan and Rob Pike present
# this code for matching simple regular expressions consisting of literal
# characters, a dot matching any character, a star consisting of zero or more
# repetitions of the preceding character, and a caret and a dollar sign
# representing the beginning or end of the search string:
#
# /* match: search for re anywhere in text */
# int match(char *re, char *text)
# {
# if (re[0] == '^')
# return matchhere(re+1, text);
# do { /* must look at empty string */
# if (matchhere(re, text))
# return 1;
# } while (*text++ != '\0');
# return 0;
# }
#
# /* matchhere: search for re at beginning of text */
# int matchhere(char *re, char *text)
# {
# if (re[0] == '\0')
# return 1;
# if (re[1] == '*')
# return matchstar(re[0], re+2, text);
# if (re[0] == '$' && re[1] == '\0')
# return *text == '\0';
# if (*text!='\0' && (re[0]=='.' || re[0]==*text))
# return matchhere(re+1, text+1);
# return 0;
# }
#
# /* matchstar: search for c*re at beginning of text */
# int matchstar(int c, char *re, char *text)
# {
# do { /* a * matches zero or more instances */
# if (matchhere(re, text))
# return 1;
# } while (*text!='\0' && (*text++==c || c=='.'));
# return 0;
# }
#
# Your task is to port the code to your favorite language. You should use the
# features and idioms of your language, while simultaneously preserving the
# beauty of Rob Pike’s regular expression matcher. When you are finished, you are
# welcome to read or run a suggested solution, or to post your solution or
# discuss the exercise in the comments below.
module Enumerable
def tail ; drop(1) ; end
end
def match(regex, string)
_match(regex.chars, string.chars)
end
def _match(re, text)
return match_here(re.tail, text) if re.first == '^'
return false if text.empty?
return true if match_here(re, text)
_match(re, text.tail)
end
def match_here(re, text)
return match_star(re.first, re.drop(2), text) if re[1] == '*'
return text.empty? if re.first == '$'
return match_here(re.tail, text.tail) if text.any? && char_match?(re.first, text.first)
re.empty?
end
def match_star(c, re, text)
return true if match_here(re, text)
return false if text.empty? || !char_match?(c, text.first)
match_star(c, re, text.tail)
end
def char_match?(l, r)
l == r || l == '.'
end
# Test code
def test(subject, target, message)
result = (subject == target) ? 'YES' : 'NOP'
puts "#{result} #{subject.inspect} = #{target.inspect} : #{message}"
end
test match("a", "a"), true, '("a", "a")'
test match("a", "b"), false, '("a", "b")'
test match("a", "ab"), true, '("a", "ab")'
test match("a", "ba"), true, '("a", "ba")'
test match("ab", "ab"), true, '("ab", "ab")'
test match("ab", "ba"), false, '("ab", "ba")'
test match("ab", "xab"), true, '("ab", "xab")'
test match("ab", "aab"), true, '("ab", "aab")'
test match("a.c", "ac"), false, '("a.c", "ac")'
test match("a.c", "abc"), true, '("a.c", "abc")'
test match("a.c", "xac"), false, '("a.c", "xac")'
test match("a.c", "xabcx"), true, '("a.c", "xabcx")'
test match("^ab", "ab"), true, '("^ab", "ab")'
test match("^ab", "ba"), false, '("^ab", "ba")'
test match("^ab", "aab"), false, '("^ab", "aab")'
test match("^ab", "abc"), true, '("^ab", "abc")'
test match("ab$", "ab"), true, '("ab$", "ab")'
test match("ab$", "ba"), false, '("ab$", "ba")'
test match("ab$", "aab"), true, '("ab$", "aab")'
test match("ab$", "abc"), false, '("ab$", "abc")'
test match("^ab$", "ab"), true, '("^ab$", "ab")'
test match("^ab$", "ba"), false, '("^ab$", "ba")'
test match("^ab$", "abc"), false, '("^ab$", "abc")'
test match("^ab$", "aba"), false, '"^ab$", "aba")'
test match("a.*c", "ac"), true, '("a.*c", "ac")'
test match("a.*c", "abc"), true, '("a.*c", "abc")'
test match("a.*c", "abbc"), true, '("a.*c", "abbc")'
test match("a.*c", "cbba"), false, '("a.*c", "cbba")'
test match("aa*", "x"), false, '("aa*", "x")'
test match("aa*", "a"), true, '("aa*", "a")'
test match("aa*", "aa"), true, '("aa*", "aa")'
test match("aa*", "ba"), true, '("aa*", "ba")'
test match("a*a*a", "a"), true, '("a*a*a", "a")'
test match("a*a*a", "aaa"), true, '("a*a*a", "aaa")'
test match("a*a*a", "xxxxx"), false, '("a*a*a", "xxxxx")'
test match("a*a*a", "xxxxx"), false, '("a*a*a", "xxxxx")'
| true |
2c05af8b4deffe50e487022e7f57c10c6db04e8f
|
Ruby
|
dereke/proxy-server
|
/lib/proxy/port_prober.rb
|
UTF-8
| 265 | 2.90625 | 3 |
[] |
no_license
|
# lovingly reused from selenium-webdriver
class PortProber
def self.above(port)
port += 1 until free? port
port
end
def self.free?(port)
TCPServer.new('localhost', port).close
true
rescue SocketError, Errno::EADDRINUSE
false
end
end
| true |
e83d88aaaf7ed27c33cfda83fe8540d5cffeb274
|
Ruby
|
ChrisCPO/Metis-Prework
|
/xis.rb
|
UTF-8
| 162 | 3.765625 | 4 |
[] |
no_license
|
puts "give me a number"
x= gets.chomp.to_i
if x > 2
puts "x is greater then 2"
elsif x < 2 and x != 0
puts "x is 1"
else
puts "i cant guess the number"
end
| true |
2cc5fe24519c49d17ecfa8a66c83093d6fd2fe6b
|
Ruby
|
alsabater/Hackerrank_30_Days_of_Code
|
/Grades_calculator.rb
|
UTF-8
| 814 | 3.859375 | 4 |
[] |
no_license
|
class Student
def initialize(firstName,lastName,phone)
@firstName=firstName
@lastName=lastName
@phone=phone
end
def display()
print("First Name: ",@firstName,"Last Name: ",@lastName+"Phone: ",@phone)
end
end
class Grade <Student
def initialize (firstName,lastName,phone,score)
super(firstName,lastName,phone)
@score = score.to_f
end
def calculate
case @score
when 0...40
return "D"
when 40...60
return "B"
when 60...75
return "A"
when 75...90
return "E"
when 90..100
return "O"
end
end
end
firstName=gets
lastName=gets
phone=gets.to_i
score=gets.to_i
g=Grade.new(firstName,lastName,phone,score)
g.display
print("\nGrade: ",g.calculate)
| true |
59eb25435091ebf9d2e748a5c461731719e92537
|
Ruby
|
allolex/nacre
|
/lib/nacre/concerns/inflectible.rb
|
UTF-8
| 765 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
module Nacre::Inflectible
CAMEL_CASE_RE = /(?<=[a-z])[A-Z]/
SNAKE_CASE_RE = /_(\w)/
def snake_case(value)
value.to_s.split(/(?=[A-Z])/).join("_").downcase
end
def camelize(value)
value = value.to_s
return value unless snake_case?(value)
value.gsub(/_(\w)/) { $1.upcase }
end
def format_hash_keys(value)
case value
when Hash
Hash[value.map { |k, v| [fix_key(k), format_hash_keys(v)] }]
when Array
value.map { |v| format_hash_keys(v) }
else
value
end
end
def fix_key(key)
if camel_case?(key)
snake_case(key).to_sym
else
key.downcase.to_sym
end
end
def camel_case?(key)
CAMEL_CASE_RE === key
end
def snake_case?(key)
SNAKE_CASE_RE === key
end
end
| true |
a3cc1d8079be5eafbccd072809a30ee915875a45
|
Ruby
|
mocoso/roman-cart
|
/lib/roman_cart_site.rb
|
UTF-8
| 2,291 | 2.625 | 3 |
[] |
no_license
|
require 'tmpdir'
require 'mechanize'
require 'roman_cart_export'
class RomanCartSite
def initialize
self.agent = Mechanize.new
end
def login(options)
login_page = agent.get('https://admin.romancart.com')
login_form = login_page.form_with(:name => 'frmlogin')
login_form.set_fields(options)
result_page = agent.submit(login_form, login_form.button_with(:value => 'Log In'))
unless result_page.title == 'RomanCart - Logging in'
raise('Unable to log in')
end
self.session_query_string = agent.history.last.uri.query
end
def data_export(from_date, to_date)
export_form_page = agent.get("https://admin.romancart.com/v111/manage/salesman/exportsales.asp?#{session_query_string}")
export_form = export_form_page.form_with(:name => 'expform')
export_form.set_fields(
:dateFrom => from_date.strftime("%d-%b-%Y"),
:dateTo => to_date.strftime("%d-%b-%Y"),
:exporttype => 3,
:sdelimiter => 1
)
# Choose to quote values in CSV (otherwise comma's in addresses cause problems)
export_form.checkboxes.detect { |c| c.name = 'dblquotes' }.checked = true
# Not sure why mechanize does not pick up these hidden fields which are in the form HTML
# however setting them manually because it doesn't
export_form.add_field!('posted', 'OK')
args = session_query_string.split('=')
export_form.add_field!(args.shift, args.join('='))
exported_page = agent.submit(export_form)
zip_link = exported_page.links.detect{ |l| l.text == 'here' }
if zip_link
# GET data export file request -> getting the data
tmp_zip_file = ::File.join(Dir.tmpdir, 'data.zip')
puts "Download zip to #{tmp_zip_file}"
zip_file = zip_link.click
zip_file.save_as tmp_zip_file
puts "Combining data files"
data_export = RomanCartExport.new(tmp_zip_file).combined_data
puts "Delete #{tmp_zip_file}"
system "rm #{tmp_zip_file}"
data_export
else
# There are no recent sales
CSV.new ''
end
end
private
# This query appears to be part of the roman carts session info. Security
# feature? Either way without it you get redirected back to the home page.
attr_accessor :session_query_string
attr_accessor :agent
end
| true |
6b1e837513a203c505d7ac9273610f457bd96e00
|
Ruby
|
chris241/THP1_J10
|
/lib/eventcreator.rb
|
UTF-8
| 709 | 3.25 | 3 |
[] |
no_license
|
class EventCreator
attr_accessor :title , :start_date, :duration, :attendees
def initialititleze(title, start_date, duration, attendees)
@title = title
@start_date = start_date
@duration = duration
@attendees = attendees
end
def recupere
puts "Salut, tu veux créer un événement? Cool!"
puts "Commençon, Quel est le nom de l'événement"
@title = gets.chomp
puts "Super. Quand aura-t-il lieu?"
@start_date = gets.chomp
puts "Au top. Combien de temps va-t-il durer (en minutes) ? "
@duration = gets.chomp.to_i
puts "Génial. Qui va participer ? Balance leurs e-mails"
@attendees = gets.chomp
end
puts "Super, c'est noté, ton évènement a été crée"
end
| true |
750f5f5386bdc8396b93406a3611f8257f049c14
|
Ruby
|
ajLapid718/HackerRank-30-Days-of-Code
|
/Day-27-Testing.rb
|
UTF-8
| 988 | 3.546875 | 4 |
[] |
no_license
|
Task
# Link: https://www.hackerrank.com/challenges/30-testing/problem
Create and print a test case for the problem above that meet the following criteria:
- A minimum of five test cases
- A number n between 3 and 200, which represents the amount of students in the class
- A number k between 1 and n, which represents the cutoff point/threshold attendance of cancelling class
- The value of n must be distinct across all the test cases
- Array A must have at least 1 zero, 1 positive integer, and 1 negative integer
Output Format
Print 11 lines of output that can be read by the Professor challenge as valid input. Your test case must result in the following output when fed as input to the Professor solution found in the challenge:
YES
NO
YES
NO
YES
# My solution
puts '5' # Amount of Test Cases
puts '3 3' # YES
puts '-1 0 1'
puts '3 2' # NO
puts '-1 0 1'
puts '8 6' # YES
puts [*-1..3].join(' ')
puts '20 5' # NO
puts [*-1..6].join(' ')
puts '4 4' # YES
puts '-100 0 0 77'
| true |
b91e3ced125ff29fe287584233a8eaacac6f8e70
|
Ruby
|
complikatyed/Whatcha_Reading
|
/app/models/author.rb
|
UTF-8
| 1,421 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# class Author < ActiveRecord::Base
# attr_reader :id, :errors
# attr_accessor :name
# def initialize(name = nil)
# self.name = name
# end
# def ==(other)
# other.is_a?(Author) && other.id == self.id
# end
# def self.all
# Database.execute("select * from authors order by name ASC").map do |row|
# populate_from_database(row)
# end
# end
# def self.count
# Database.execute("select count(id) from author")[0][0]
# end
# def self.find(id)
# row = Database.execute("select * from author where id = ?", id).first
# if row.nil?
# nil
# else
# populate_from_database(row)
# end
# end
# def valid?
# if name.nil? or name.empty? or /^\d+$/.match(name)
# @errors = "\'#{name}\' is not a valid author name."
# false
# else
# @errors = nil
# true
# end
# end
# def save
# return false unless valid?
# if @id.nil?
# Database.execute("INSERT INTO authors (name) VALUES (?)", name)
# @id = Database.execute("SELECT last_insert_rowid()")[0]['last_insert_rowid()']
# true
# else
# Database.execute("UPDATE authors SET name=? WHERE id=?", name, id)
# true
# end
# end
# private
# def self.populate_from_database(row)
# author = Author.new
# author.title = row['name']
# author.instance_variable_set(:@id, row['id'])
# author
# end
# end
| true |
9284e917c459f93b8e6e5126c5238e1261c81c7c
|
Ruby
|
oscarjes/bootcamp-ruby
|
/week1/assignment/list.rb
|
UTF-8
| 1,420 | 3.671875 | 4 |
[] |
no_license
|
require 'colorize'
require_relative "item"
class List
attr_accessor :items
def initialize(name, items = [])
@name = name
@items = items
end
def add(item)
@items << item
end
def display
puts ("-" * 100).colorize(:light_blue)
puts "Here is your #{@name}:".colorize(:light_blue)
puts ("-" * 100).colorize(:light_blue)
@items.each_with_index do |item, index|
if item.done?
puts "- [x] #{item.name} (#{index + 1})".colorize(:green)
else
puts "- [ ] #{item.name} (#{index + 1})".colorize(:yellow)
end
end
end
def display_done
puts ("-" * 100).colorize(:light_blue)
puts "Here are your done tasks:".colorize(:light_blue)
puts ("-" * 100).colorize(:light_blue)
@items.each_with_index do |item, index|
if item.done?
puts "- [x] #{item.name} (#{index + 1})".colorize(:green)
end
end
end
def display_undone
puts ("-" * 100).colorize(:light_blue)
puts "Here are the tasks you haven't done yet:".colorize(:light_blue)
puts ("-" * 100).colorize(:light_blue)
@items.each_with_index do |item, index|
if item.done? == false
puts "- [ ] #{item.name} (#{index + 1})".colorize(:yellow)
end
end
end
def mark_done_at!(index)
item = @items[index]
item.done = true
end
def mark_undone_at!(index)
item = @items[index]
item.done = false
end
end
| true |
85e201cb272d08250466d59252ad1d157ccf289e
|
Ruby
|
stormbrew/channel9
|
/ruby/lib/channel9/instruction/message_new.rb
|
UTF-8
| 1,327 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
module Channel9
module Instruction
# message_new name, sys_count, count
# ---
# Pushes a message onto the stack, with count
# positional arguments consumed and stored in the argument
# pack, along with the message name.
#
# Takes count inputs as well as a message name:
# SP ->arg1 -> arg2 ... -> argN -> sys_arg1 -> sys_arg2 ... -> sys_argN
# Leaves the message on the stack:
# SP -> message
#
# Messages are one of the primitive types in channel9.
# They facilitate sending messages that will be dispatched on
# name (or other traits) to an object (represented by a channel).
# All objects in channel9 are channels, and messages are the
# primative by which they communicate.
class MESSAGE_NEW < Base
def initialize(stream, name, sys_count, count)
super(stream, sys_count + count, 1)
@name = name
@sys_count = sys_count
@count = count
end
def arguments
[@name, @sys_count, @count]
end
def run(env)
sys_args = []
args = []
@count.times { args.unshift(env.context.pop) }
@sys_count.times { sys_args.unshift(env.context.pop) }
message = Primitive::Message.new(@name, sys_args, args)
env.context.push(message)
end
end
end
end
| true |
f5ea0c360cf33a5c3ea92b1451f4a8a7ae2526fb
|
Ruby
|
yu-nakagawa/design-pattern
|
/abstract_factory.rb
|
UTF-8
| 1,500 | 4.0625 | 4 |
[] |
no_license
|
class Duck
def initialize(name)
@name = name
end
def eat
puts "アヒル #{@name} は食事中です"
end
end
class Frog
def initialize(name)
@name = name
end
def eat
puts "カエル #{@name} は食事中です"
end
end
class WaterLily
def initialize(name)
@name = name
end
def grow
puts "スイレン#{@name}は成長中"
end
end
class Algae
def initialize(name)
@name = name
end
def grow
puts "藻#{@name}は成長中"
end
end
class OrganismFactory
def initialize(number_animals, number_plants)
@animals = []
number_animals.times do |i|
animal = new_animal("動物#{i}")
@animals << animal
end
@plants = []
number_plants.times do |i|
plant = new_plant("植物#{i}")
@plants << plant
end
end
def get_animals
@animals
end
def get_plants
@plants
end
end
class FrogAndAlgaeFactory < OrganismFactory
private
def new_animal(name)
Frog.new(name)
end
def new_plant(name)
Algae.new(name)
end
end
class DuckAndWaterLilyFactory < OrganismFactory
private
def new_animal(name)
Duck.new(name)
end
def new_plant(name)
WaterLily.new(name)
end
end
factory = FrogAndAlgaeFactory.new(2, 1)
animals = factory.get_animals
animals.each(&:eat)
plants = factory.get_plants
plants.each(&:grow)
factory = DuckAndWaterLilyFactory.new(2, 1)
animals = factory.get_animals
animals.each(&:eat)
plants = factory.get_plants
plants.each(&:grow)
| true |
9c3ef1dbee5e1941aa31d7f958c538a6fa1625f3
|
Ruby
|
roman-franko/fog_backup
|
/lib/fog_backup/base.rb
|
UTF-8
| 1,719 | 2.53125 | 3 |
[] |
no_license
|
module FogBackup
class Base
include Helpers::Archiver
include Helpers::Aws
include Helpers::Ftp
def initialize
@timestamp = Time.now
set_local_storage
@archive_path = File.join(@tmp_dir, "#{formatted_time @timestamp}.tar.gz")
end
def run
target_dir = FogBackup.config['ftp']['target_dir']
target_dir = target_dir[-1] == '/' ? target_dir.chop : target_dir
download_from_ftp(@local_dir, target_dir)
tar(@tmp_dir, formatted_time(@timestamp), @archive_path)
upload_to_aws(@archive_path)
Pony.mail(
:subject => "Successful backup, time: #{@timestamp}",
:body => %Q(
Spent time: #{spent_time};
Archive size: #{archive_size};
))
rescue => e
Pony.mail(
:subject => "Failure backup, time: #{@timestamp}",
:body => "Failure backup with error: #{e.message}")
ensure
FileUtils.rm_rf(@local_dir) if File.directory?(@local_dir)
File.delete(@archive_path) if File.exist?(@archive_path)
end
private :tar, :untar, :upload_to_aws, :download_from_ftp
def formatted_time(t)
t.strftime("%Y-%m-%d_%H:%M:%S_UTC")
end
def spent_time
finish = Time.now
elapsed = finish.to_f - @timestamp.to_f
mins, secs = elapsed.divmod 60.0
"%d:%04.2f" % [mins.to_i, secs]
end
def archive_size
"%.#{0}f KB" % [File.size?(@archive_path)/1024.0]
end
def set_local_storage
@tmp_dir = FogBackup.config['options']['tmp_dir']
@local_dir = File.join @tmp_dir, formatted_time(@timestamp)
FileUtils.mkdir_p(@local_dir) unless File.directory?(@local_dir)
end
end
end
| true |
0dd57378fa803e900e39bd9d6abd431fb55003f5
|
Ruby
|
pcarri4/programming-univbasics-nds-green-grocer-part-1-chi01-seng-ft-120720
|
/lib/grocer.rb
|
UTF-8
| 487 | 3.046875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def find_item_by_name_in_collection(name, collection)
# Implement me first!
#
# Consult README for inputs and outputs
cart = nil
collection.each do |item|
if item[:item] == name
cart = item
end
end
cart
end
def consolidate_cart(cart)
receipt = Array.new
cart.each do |item|
count = 0
if !item[:count]
item[:count] = count
end
if item[:item]
item[:count] += 1
end
if item[:count] > 0
receipt << item
end
end
receipt
end
| true |
6939a6f79a3695390b9f2ea0e7d35f2d2e8d27a1
|
Ruby
|
mikeisfake/prime-ruby-online-web-pt-081219
|
/prime.rb
|
UTF-8
| 89 | 3.328125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(num)
return false if num <= 1
(2..num - 1).none?{ |i| num % i == 0}
end
| true |
4ca298f22b41ed462811edecddd0b67636915cd2
|
Ruby
|
voxpupuli/beaker
|
/spec/beaker/command_spec.rb
|
UTF-8
| 5,337 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'spec_helper'
module Beaker
describe Command do
subject(:cmd) { described_class.new(command, args, options) }
let(:command) { @command || '/bin/ls' }
let(:args) { @args || [] }
let(:options) { @options || {} }
let(:host) do
h = {}
allow(h).to receive(:environment_string).and_return('')
h
end
it 'creates a new Command object' do
@command = '/usr/bin/blah'
@args = %w[to the baz]
@options = { :foo => 'bar' }
expect(cmd.options).to be == @options
expect(cmd.args).to be == @args
expect(cmd.command).to be == @command
expect(cmd.args_string).to be == 'to the baz'
expect(cmd.options_string).to be == '--foo=bar'
end
describe '#:prepend_cmds' do
it 'can prepend commands' do
@command = '/usr/bin/blah'
@args = %w[to the baz]
@options = { :foo => 'bar' }
allow(host).to receive(:prepend_commands).and_return('aloha!')
allow(host).to receive(:append_commands).and_return('')
expect(cmd.cmd_line(host)).to be == "aloha! /usr/bin/blah --foo=bar to the baz"
end
it 'can handle no prepend_cmds' do
@command = '/usr/bin/blah'
@args = %w[to the baz]
@options = { :foo => 'bar' }
allow(host).to receive(:prepend_commands).and_return('')
allow(host).to receive(:append_commands).and_return('')
expect(cmd.cmd_line(host)).to be == "/usr/bin/blah --foo=bar to the baz"
end
end
describe '#:append_commands' do
it 'can append commands' do
@command = '/usr/bin/blah'
@args = %w[to the baz]
@options = { :foo => 'bar' }
allow(host).to receive(:prepend_commands).and_return('aloha!')
allow(host).to receive(:append_commands).and_return('moo cow')
expect(cmd.cmd_line(host)).to be == "aloha! /usr/bin/blah --foo=bar to the baz moo cow"
end
it 'can handle no append_cmds' do
@command = '/usr/bin/blah'
@args = %w[to the baz]
@options = { :foo => 'bar' }
allow(host).to receive(:prepend_commands).and_return('')
allow(host).to receive(:append_commands).and_return('')
expect(cmd.cmd_line(host)).to be == "/usr/bin/blah --foo=bar to the baz"
end
end
describe '#options_string' do
it 'parses things' do
subject.options = { :v => nil, :test => nil,
:server => 'master', :a => 'answers.txt', }
expect(subject.options_string).to match(/-v/)
expect(subject.options_string).to match(/--test/)
expect(subject.options_string).to match(/--server=master/)
expect(subject.options_string).to match(/-a=answers\.txt/)
end
end
describe '#args_string' do
it 'joins an array' do
subject.args = ['my/command and', nil, 'its args and opts']
expect(subject.args_string).to be == 'my/command and its args and opts'
end
end
end
describe HostCommand do
subject(:cmd) { described_class.new(command, args, options) }
let(:command) { @command || '/bin/ls' }
let(:args) { @args || [] }
let(:options) { @options || {} }
let(:host) { {} }
it 'returns a simple string passed in' do
@command = "pants"
expect(cmd.cmd_line host).to be === @command
end
it 'returns single quoted string correctly' do
@command = "str_p = 'pants'; str_p"
expect(cmd.cmd_line host).to be === @command
end
it 'returns empty strings when given the escaped version of the same' do
@command = "\"\""
expect(cmd.cmd_line host).to be === ""
end
end
describe SedCommand do
subject(:cmd) { described_class.new(platform, expression, filename, options) }
let(:host) do
h = {}
allow(h).to receive(:environment_string).and_return('')
allow(h).to receive(:prepend_commands).and_return('')
allow(h).to receive(:append_commands).and_return('')
h
end
let(:platform) { @platform || 'unix' }
let(:expression) { @expression || 's/b/s/' }
let(:filename) { @filename || '/fakefile' }
let(:options) { @options || {} }
it 'forms a basic sed command correctly' do
expect(cmd.cmd_line host).to be === "sed -i -e \"#{expression}\" #{filename}"
end
it 'provides the -i option to rewrite file in-place on non-solaris hosts' do
expect(cmd.cmd_line host).to include('-i')
end
describe 'on solaris hosts' do
it 'removes the -i option correctly' do
@platform = 'solaris'
expect(cmd.cmd_line host).not_to include('-i')
end
it 'deals with in-place file substitution correctly' do
@platform = 'solaris'
default_temp_file = "#{filename}.tmp"
expect(cmd.cmd_line host).to include(" > #{default_temp_file} && mv #{default_temp_file} #{filename} && rm -f #{default_temp_file}")
end
it 'allows you to provide the name of the temp file for in-place file substitution' do
@platform = 'solaris'
temp_file = 'mytemp.tmp'
@options = { :temp_file => temp_file }
expect(cmd.cmd_line host).to include(" > #{temp_file} && mv #{temp_file} #{filename} && rm -f #{temp_file}")
end
end
end
end
| true |
cb24d3fdef33e8ca3eb5ef97cc261a1128f4ae48
|
Ruby
|
kolishchak/codewars
|
/Design Patterns/elevator.rb
|
UTF-8
| 952 | 3.578125 | 4 |
[] |
no_license
|
module ValuesValidator
def valid?
self.value.is_a?(valid_type) && self.valid_values.include?(value)
end
end
class Level
include ValuesValidator
attr_reader :value
def initialize(value)
@value = value
end
def valid_values
(0..3)
end
def valid_type
Integer
end
end
class Button
include ValuesValidator
attr_reader :value
def initialize(value)
@value = value
end
def valid_values
('0'..'3')
end
def valid_type
String
end
end
class Elevator
REMAIN_LEVEL = 0
attr_reader :level, :button
def initialize(level, button)
@level = Level.new(level)
@button = Button.new(button)
end
def call
return REMAIN_LEVEL if erroneous_input?
up_down_level
end
private
def erroneous_input?
!(level.valid? && button.valid?)
end
def up_down_level
button.value.to_i - level.value
end
end
def goto(level, button)
Elevator.new(level, button).call
end
| true |
4380c5038ebd65ecb52b2e062937a1e081ee4b51
|
Ruby
|
vinbarnes/asciidoctor
|
/test/headers_test.rb
|
UTF-8
| 4,261 | 2.828125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require 'test_helper'
context "Headers" do
test "document title with multiline syntax" do
title = "My Title"
chars = "=" * title.length
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars)
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n")
end
test "document title with multiline syntax, give a char" do
title = "My Title"
chars = "=" * (title.length + 1)
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars)
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n")
end
test "document title with multiline syntax, take a char" do
title = "My Title"
chars = "=" * (title.length - 1)
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars)
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n")
end
test "not enough chars for a multiline document title" do
title = "My Title"
chars = "=" * (title.length - 2)
assert_xpath '//h1', render_string(title + "\n" + chars), 0
assert_xpath '//h1', render_string(title + "\n" + chars + "\n"), 0
end
test "too many chars for a multiline document title" do
title = "My Title"
chars = "=" * (title.length + 2)
assert_xpath '//h1', render_string(title + "\n" + chars), 0
assert_xpath '//h1', render_string(title + "\n" + chars + "\n"), 0
end
test "document title with single-line syntax" do
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string("= My Title")
end
test "document title with symmetric syntax" do
assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string("= My Title =")
end
context "level 1" do
test "with multiline syntax" do
assert_xpath "//h2[@id='_my_section'][text() = 'My Section']", render_string("My Section\n-----------")
end
test "with single-line syntax" do
assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title")
end
test "with single-line symmetric syntax" do
assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title ==")
end
test "with single-line non-matching symmetric syntax" do
assert_xpath "//h2[@id='_my_title'][text() = 'My Title ===']", render_string("== My Title ===")
end
test "with non-word character" do
assert_xpath "//h2[@id='_where_s_the_love'][text() = \"Where's the love?\"]", render_string("== Where's the love?")
end
test "with sequential non-word characters" do
assert_xpath "//h2[@id='_what_the_is_this'][text() = 'What the \#@$ is this?']", render_string('== What the #@$ is this?')
end
test "with trailing whitespace" do
assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title ")
end
test "with custom blank idprefix" do
assert_xpath "//h2[@id='my_title'][text() = 'My Title']", render_string(":idprefix:\n\n== My Title ")
end
test "with custom non-blank idprefix" do
assert_xpath "//h2[@id='ref_my_title'][text() = 'My Title']", render_string(":idprefix: ref_\n\n== My Title ")
end
end
context "level 2" do
test "with multiline syntax" do
assert_xpath "//h3[@id='_my_section'][text() = 'My Section']", render_string("My Section\n~~~~~~~~~~~")
end
test "with single line syntax" do
assert_xpath "//h3[@id='_my_title'][text() = 'My Title']", render_string("=== My Title")
end
end
context "level 3" do
test "with multiline syntax" do
assert_xpath "//h4[@id='_my_section'][text() = 'My Section']", render_string("My Section\n^^^^^^^^^^")
end
test "with single line syntax" do
assert_xpath "//h4[@id='_my_title'][text() = 'My Title']", render_string("==== My Title")
end
end
context "level 4" do
test "with multiline syntax" do
assert_xpath "//h5[@id='_my_section'][text() = 'My Section']", render_string("My Section\n++++++++++")
end
test "with single line syntax" do
assert_xpath "//h5[@id='_my_title'][text() = 'My Title']", render_string("===== My Title")
end
end
end
| true |
c3f1716382b16daf891b9510a1525ec33c37bc16
|
Ruby
|
justinweiss/error_stalker
|
/lib/error_stalker/store/in_memory.rb
|
UTF-8
| 3,337 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
require 'error_stalker/store/base'
require 'will_paginate/array'
require 'set'
# The simplest exception store. This just stores each reported
# exception in a list held in memory. This, of course, means that the
# exception list will disappear when the server goes down, the server
# might take up tons of memory, and searching will probably be
# slow. In other words, this is a terrible choice for production. On
# the other hand, this store is especially useful for tests.
class ErrorStalker::Store::InMemory < ErrorStalker::Store::Base
# The list of exceptions reported so far.
attr_reader :exceptions
# A hash of exceptions indexed by digest.
attr_reader :exception_groups
# All the machines that have seen exceptions
attr_reader :machines
# All the applications that have seen exceptions
attr_reader :applications
# Creates a new instance of this store.
def initialize
clear
end
# Store +exception_report+ in the exception list. This also indexes
# the exception into the appropriate exception group.
def store(exception_report)
@exceptions << exception_report
self.machines << exception_report.machine
self.applications << exception_report.application
exception_report.id = exceptions.length - 1
exception_groups[exception_report.digest] ||= []
exception_groups[exception_report.digest] << exception_report
exception_report.id
end
# Returns a list of exceptions whose digest is +digest+.
def reports_in_group(digest)
exception_groups[digest]
end
# returns the exception group matching +digest+
def group(digest)
build_group_for_exceptions(reports_in_group(digest))
end
# Empty this exception store. Useful for tests!
def clear
@exceptions = []
@exception_groups = {}
@machines = Set.new
@applications = Set.new
end
# Searches for exception reports maching +params+.
def search(params = {})
results = exceptions
results = results.select {|e| e.machine == params[:machine]} if params[:machine] && !params[:machine].empty?
results = results.select {|e| e.application == params[:application]} if params[:application] && !params[:application].empty?
results = results.select {|e| e.exception.to_s =~ /#{params[:exception]}/} if params[:exception] && !params[:exception].empty?
results = results.select {|e| e.type.to_s =~ /#{params[:type]}/} if params[:type] && !params[:type].empty?
results.reverse
end
# Find an exception report with the given id.
def find(id)
exceptions[id.to_i]
end
# Have we logged any exceptions?
def empty?
exceptions.empty?
end
# Return recent exceptions grouped by digest.
def recent
data = []
exception_groups.map do |digest, group|
data << build_group_for_exceptions(group)
end
data.reverse
end
def total
@exceptions.count
end
def total_since(timestamp)
@exceptions.select { |e| e.timestamp >= timestamp.to_s }.length
end
protected
def build_group_for_exceptions(group)
ErrorStalker::ExceptionGroup.new.tap do |g|
g.count = group.length
g.digest = group.first.digest
g.machines = group.map(&:machine).uniq
g.first_timestamp = group.first.timestamp
g.most_recent_timestamp = group.last.timestamp
g.most_recent_report = group.last
end
end
end
| true |
4225925e483765f7d2ad3b5e8d46ca8fd259c2f5
|
Ruby
|
panickat/CodeaCampRuby
|
/sem1/dia4/6_hash_iteracion.rb
|
UTF-8
| 438 | 3.53125 | 4 |
[] |
no_license
|
def family_members(h)
respuesta = []
h.each do |k,v|
respuesta.concat(v) if (k == :sisters || k == :brothers)
end
respuesta
end
family = { uncles: ["jorge", "samuel", "steve"],
sisters: ["angelica", "mago", "julia"],
brothers: ["polo","rob","david"],
aunts: ["maria","minerva","susana"]
}
#test
p family_members(family) == ["angelica", "mago", "julia", "polo", "rob", "david"]
| true |
f4936b04b0936fe82dcfbae2e5f0912ace36f06c
|
Ruby
|
kinisoftware/7L7W
|
/Ruby/day2/array_four_items_at_time_with_each_slice.rb
|
UTF-8
| 39 | 3.078125 | 3 |
[] |
no_license
|
(1..16).each_slice(4) {|items| p items}
| true |
1fec76d20cee952e0d0feeff6f2437b26327c1f7
|
Ruby
|
micahbf/rails_lite
|
/lib/rails_lite/controller_base.rb
|
UTF-8
| 1,076 | 2.546875 | 3 |
[] |
no_license
|
require 'erb'
require_relative 'params'
require_relative 'session'
class ControllerBase
attr_reader :params
def initialize(req, res, router_params)
@request = req
@response = res
@params = Params.new(req, router_params)
end
def session
@session ||= Session.new(@request)
end
def already_rendered?
@already_built_response || false
end
def redirect_to(url)
@response.status = 302
@response['Location'] = url
session.store_session(@response)
@already_built_response = true
end
def render_content(content, type)
@response['Content-Type'] = type
@response.body = content
session.store_session(@response)
@already_built_response = true
end
def render(template_name)
file_path = "views/#{self.class.name.underscore}/#{template_name}.html.erb"
template = ERB.new(File.read(file_path))
rendered = template.result(binding)
render_content(rendered, 'text/html')
end
def invoke_action(action_name)
self.send(action_name)
render(action_name) unless already_rendered?
end
end
| true |
2a8c91ded92686a4051a17d12d264d2d75adf278
|
Ruby
|
llwebsol/omg_validator
|
/test/alpha_numeric_validator_test.rb
|
UTF-8
| 776 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
require 'test_helper'
class AlphaNumericValidatorTest < ActiveSupport::TestCase
def setup
@thing = Thing.new
@things = Things.new
end
def teardown
@thing = nil
end
test 'Thing should be valid if alpha_numeric attribute has alphanumeric characters.' do
@things.alpha_numeric['valid'].each do |string|
@thing.alpha_numeric = string.to_s
assert @thing.valid?, string.to_s << ' - ' << @thing.errors.full_messages.join('\n')
end
end
test 'Thing should be invalid if alpha_numeric attribute has non-alphanumeric characters.' do
@things.alpha_numeric['invalid'].each do |string|
@thing.alpha_numeric = string.to_s
assert [email protected]?, string.to_s << ' - ' << @thing.errors.full_messages.join('\n')
end
end
end
| true |
e1f4b21f0ef496b31461250b064205d3368bc7e7
|
Ruby
|
blackric/steam-condenser
|
/ruby/lib/steam/community/app_news.rb
|
UTF-8
| 2,541 | 2.765625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2010-2011, Sebastian Staudt
require 'json'
require 'steam/community/web_api'
# The AppNews class is a representation of Steam news and can be used to load
# current news about specific games
class AppNews
attr_reader :app_id, :author, :contents, :date, :feed_label, :feed_name,
:gid, :title, :url
# Loads the news for the given game with the given restrictions
#
# [+app_id+] The unique Steam Application ID of the game (e.g. +440+ for
# Team Fortress 2). See
# http://developer.valvesoftware.com/wiki/Steam_Application_IDs
# for all application IDs
# [+count+] The maximum number of news to load (default: 5). There's no
# reliable way to load all news. Use really a really great
# number instead
# [+max_length+] The maximum content length of the news (default: nil). If a
# maximum length is defined, the content of the news will only
# be at most +max_length+ characters long plus an ellipsis
def self.news_for_app(app_id, count = 5, max_length = nil)
params = { :appid => app_id, :count => count, :maxlength => max_length }
data = WebApi.json('ISteamNews', 'GetNewsForApp', 2, params)
news_items = []
JSON.parse(data, { :symbolize_names => true })[:appnews][:newsitems].each do |news_data|
news_items << AppNews.new(app_id, news_data)
end
news_items
end
# Returns whether this news items originates from a source other than Steam
# itself (e.g. an external blog)
def external?
@external
end
private
# Creates a new instance of an AppNews news item with the given data
#
# [+app_id+] The unique Steam Application ID of the game (e.g. +440+ for
# Team Fortress 2). See
# http://developer.valvesoftware.com/wiki/Steam_Application_IDs
# for all application IDs
# [+news_data+] The news data extracted from JSON
def initialize(app_id, news_data)
@app_id = app_id
@author = news_data[:author]
@contents = news_data[:contents].strip
@data = Time.at(news_data[:date])
@external = news_data[:is_external_url]
@feed_label = news_data[:feedlabel]
@feed_name = news_data[:feedname]
@gid = news_data[:gid]
@title = news_data[:title]
@url = news_data[:url]
end
end
| true |
1e070d687d9ad3ad2263a7b04c72c05e04586dfa
|
Ruby
|
rshea303/sales_engine
|
/lib/transaction.rb
|
UTF-8
| 887 | 2.546875 | 3 |
[] |
no_license
|
require_relative 'support'
class Transaction
include Support
attr_reader :id,
:invoice_id,
:credit_card_number,
:credit_card_expiration_date,
:result,
:created_at,
:updated_at,
:repository
def initialize(data, parent)
@id = data[:id].to_i
@invoice_id = data[:invoice_id].to_i
@credit_card_number = data[:credit_card_number]
@credit_card_expiration_date = data[:credit_card_expiration_date]
@result = data[:result]
@created_at = date_scrubber(data[:created_at])
@updated_at = date_scrubber(data[:updated_at])
@repository = parent
end
def invoice
repository.find_invoice(invoice_id)
end
end
| true |
f92bbfa85394ccb73dc17a34140f8909c5bf2c07
|
Ruby
|
chrisjgilbert/fizzbuzz-ruby
|
/spec/fizzbuzz_spec.rb
|
UTF-8
| 509 | 3.375 | 3 |
[] |
no_license
|
require 'fizzbuzz'
describe FizzBuzz do
describe '#play' do
it 'returns Fizz if number is divisible by 3' do
expect(subject.play(3)).to eq 'Fizz'
end
it 'returns Buzz if number is divisible by 5' do
expect(subject.play(5)).to eq 'Buzz'
end
it 'returns FizzBuzz if number is divisible by 15' do
expect(subject.play(15)).to eq 'FizzBuzz'
end
it 'returns number if number not divisible by 3, 5, 15' do
expect(subject.play(7)).to eq 7
end
end
end
| true |
3b3451a837bed611bc78ecd81c6258df36d32bb6
|
Ruby
|
pitosalas/coursegen
|
/lib/coursegen/course/schedule/schedule_def.rb
|
UTF-8
| 535 | 2.90625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Define schedule scheme for a lecture series
class ScheduleDef
attr_reader :first_day, :weekdays, :number, :skips, :start_time, :end_time, :start_times, :end_times
def initialize(first_day: nil, weekdays: nil, number: nil,
skips: [], start_time: nil, end_time: nil, start_times: [], end_times: [])
@first_day = first_day
@weekdays = weekdays
@number = number
@skips = skips
@start_time = start_time
@end_time = end_time
@start_times = start_times
@end_times = end_times
end
end
| true |
aeefdcc706eeeaf44699e7e318ece5dfa56f3959
|
Ruby
|
puppetpies/Snippets
|
/keyword_highlight.rb
|
UTF-8
| 376 | 3.203125 | 3 |
[] |
no_license
|
a = "Linux, Android, some text Java Mobile hello this is just a test, DevOps, far to much fun!"
def text_highlighter(text)
keys = ["Linux", "Java", "Android", "DevOps", "obi", "uc", "un!", "us"]
cpicker = [2,3,4,1,3]
keys.each {|n|
text.gsub!("#{n}", "\e[4;3#{cpicker[rand(cpicker.size)]}m#{n}\e[0m\ ".strip)
}
puts text
end
10.times {
text_highlighter(a)
}
| true |
a3759ec6464ca1f2e600cae5206d0b8e2903a6cf
|
Ruby
|
ga-wolf/WDI12_Homework
|
/AlexLee/week_05/games-on-rails/games/app/controllers/rps_controller.rb
|
UTF-8
| 2,804 | 2.703125 | 3 |
[] |
no_license
|
class RpsController < ApplicationController
def rock_paper_scissors_play
rock_paper_scissors_play = {
:rock => {:rock => "draw", :paper => "paper", :scissors => "rock", :lizard => "rock", :spock => "spock"},
:paper => {:rock => "paper", :paper => "draw", :scissors => "scissors", :lizard => "lizard", :spock => "paper"},
:scissors => {:rock => "rock", :paper => "scissors", :scissors => "draw", :lizard => "scissors", :spock => "spock"},
:lizard => {:rock => "rock", :paper => "lizard", :scissors => "scissors", :lizard => "draw", :spock => "lizard"},
:spock => {:rock => "spock", :paper => "paper", :scissors => "spock", :lizard => "lizard", :spock => "draw"}
}
if params[:throw]
options = [:rock, :paper, :scissors, :lizard, :spock]
rand = Random.new.rand(options.length)
@computer_choice = options[rand]
@player_choice = params[:throw]
@result = rock_paper_scissors_play[@player_choice.downcase.to_sym][@computer_choice]
if @result == @player_choice
@result = "You win with #{@player_choice.capitalize}."
elsif @result == @computer_choice.to_s
@result = "Computer wins with #{@computer_choice.capitalize}."
else
@result = "It's a draw."
end
end
end
def rps_lizard_spock_play
rock_paper_scissors_play = {
:rock => {:rock => "draw", :paper => "paper", :scissors => "rock", :lizard => "rock", :spock => "spock"},
:paper => {:rock => "paper", :paper => "draw", :scissors => "scissors", :lizard => "lizard", :spock => "paper"},
:scissors => {:rock => "rock", :paper => "scissors", :scissors => "draw", :lizard => "scissors", :spock => "spock"},
:lizard => {:rock => "rock", :paper => "lizard", :scissors => "scissors", :lizard => "draw", :spock => "lizard"},
:spock => {:rock => "spock", :paper => "paper", :scissors => "spock", :lizard => "lizard", :spock => "draw"}
}
if params[:throw]
options = [:rock, :paper, :scissors, :lizard, :spock]
rand = Random.new.rand(options.length)
@computer_choice = options[rand]
@player_choice = params[:throw]
@result = rock_paper_scissors_play[@player_choice.downcase.to_sym][@computer_choice]
if @result == @player_choice
@result = "You win with "
@winner = "#{@player_choice}"
elsif @result == @computer_choice.to_s
@result = "Computer wins with "
@winner = "#{@computer_choice}"
else
@result = "It's a draw."
end
end
end
end
| true |
6c5021d7da9a64cad9f8136e458e0a6860a6118a
|
Ruby
|
vsizov/cssquirt
|
/lib/cssquirt/file_list.rb
|
UTF-8
| 1,389 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
require 'rake'
module CSSquirt
class ImageFileList < Rake::FileList
# Public: return a CSS document of all images
#
# prefix - an optional String to automatically prefix all class names with, useful
# for namespacing, etc. Default: nil.
# header - a optional Boolean value representing whether or not to include the
# "generated by" credit in the header of the CSS document. Default: true.
#
# Returns a CSS document as a String.
def to_css(prefix="example", header=true)
css_classes = self.zip(self.to_images).map do |item|
item_filelist,item_imagefile = item[0],item[1]
item_imagefile.as_css_background_with_class( prefix + "-#{item_filelist.pathmap('%n')}" )
end
header_msg = "/* Generated with CSSquirt! (http://github.com/mroth/cssquirt/) */\n"
header_msg = '' if header == false
header_msg + css_classes.join("\n")
end
# Public: map the filelist to ImageFiles, handling any errors.
# For now, this just reports errors to STDERR so they can be noted.
#
# Returns an Array of ImageFiles.
def to_images
image_map = []
self.each do |file|
begin
image_map << ImageFile.new(file)
rescue Exception => e
$stderr.puts "WARNING: skipped file - #{e.message}"
end
end
image_map
end
end
end
| true |
9294a63a386be152b0039292a708121652b3ef8a
|
Ruby
|
dell-asm/razor-server
|
/db/migrate/015_realize_node_name.rb
|
UTF-8
| 2,022 | 2.515625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
# -*- encoding: utf-8 -*-
require_relative './util'
# Node names were previously fabricated in application code as required; this
# resulted in a highly non-uniform API, and complicates validation code based
# on object references.
#
# This performs the same realization of the value into the database for
# existing nodes, and allows us to generate the appropriate value in
# the future.
Sequel.migration do
up do
extension(:constraint_validations)
# We have to allow null values, because we have no initial setting, and
# PostgreSQL does not allow deferring null value constraints in versions
# that we support. This is fixed later.
add_column :nodes, :name, :varchar, :size => 250, :null => true
from(:nodes).update(:name => Sequel.lit("'node' || id"))
# Finally, declare it to be not null, now we have a value everywhere
alter_table :nodes do
set_column_not_null :name
validate { format NAME_RX, :name, name: 'node_name_is_simple', allow_nil: true }
end
# ...and now the ugly part: we can't have a standard default value for the
# node name, since we use "node${id}", and we can't reference a column in
# a default value.
#
# The same restriction means that we can't just calculate it in the
# application code before create, since we can't generate the name without
# knowing the ID, and the ID is assigned at insert time by the database.
#
# So... this. Sorry.
run <<'SQL'
create or replace function nodes_node_name_default_trigger() returns trigger as $$
begin
if NEW.name is NULL then
NEW.name = 'node' || NEW.id;
end if;
return NEW;
end
$$ LANGUAGE plpgsql
SQL
run <<'SQL'
create trigger nodes_node_name_default_trigger
before insert on nodes
for each row
execute procedure nodes_node_name_default_trigger()
SQL
end
down do
run 'drop trigger nodes_node_name_default_trigger on nodes'
run 'drop function nodes_node_name_default_trigger()'
drop_column :nodes, :name
end
end
| true |
6b3fb0f2c5d9120db5d573118c9f4f8bc193fd97
|
Ruby
|
graywh/ccsc-se-contest
|
/2010/2/17-2.rb
|
UTF-8
| 438 | 3.25 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
data = {}
def rating(win,loss,sum)
(sum + 400.0 * (win - loss)) / (win + loss)
end
STDIN.readline.to_i.times do |line|
team, record, scores = line.split(' ', 3)
wins, loss = record.split('-').map(&:to_i)
sum = scores.split.map(&:to_i).inject(&:+)
data[team] = rating(wins,loss,sum)
end
data.sort { |a,b| b[1] <=> a[1] }.each_with_index do |(team, score), i|
puts "#{i+1})#{team} #{"%.2f" % score}"
end
| true |
9a34cb9fef93c0dd2468397f475fed1c171619a3
|
Ruby
|
jjoub/rails-longest-word-game
|
/app/controllers/games_controller.rb
|
UTF-8
| 790 | 3 | 3 |
[] |
no_license
|
require 'json'
require 'open-uri'
class GamesController < ApplicationController
def new
@letters = []
10.times do
@letters << ("A".."Z").to_a.sample
end
end
def score
@answer_player = params[:answer]
@letters_sample = params[:letters_sample]
if @answer_player.upcase.split("").all? { |elem| @letters_sample.split("").include?(elem.capitalize) && @answer_player.count(elem) <= @letters_sample.count(elem.capitalize) }
found = JSON.parse(open("https://wagon-dictionary.herokuapp.com/#{@answer_player}").read)
if found["found"] == true
@answer = "#{@answer_player} is an english word"
else
@answer = "#{@answer_player} is not an english word"
end
else
@answer = "it's not in the grid"
end
end
end
| true |
8ba29b7237130eed8268ebcfac9dec52409210f6
|
Ruby
|
rmiri/ruby-enumerables-cartoon-collections-lab-london-web-120919
|
/cartoon_collections.rb
|
UTF-8
| 677 | 3.484375 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def roll_call_dwarves(array)# code an argument here
# Your code here
myhash = Hash.new
array.each_with_index { |item,index|
myhash[index + 1] = item
}
puts myhash
end
def summon_captain_planet(names)# code an argument here
# Your code here
names.map {|name| p "#{name.capitalize}!"}
end
def long_planeteer_calls(array)# code an argument here
# Your code here
array.any? { |e| e.length > 4 }
end
def find_the_cheese(array)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
array.find { |cheese|
cheese_types.include?(cheese)
}
end
# .find(item => {
# return item.isAstronaut
# })
| true |
c9b42a5a60e9cc7b4456a6b1308db7f925f410d3
|
Ruby
|
AlinaGoaga/GildedRose
|
/spec/features/gilded_rose_spec.rb
|
UTF-8
| 944 | 2.734375 | 3 |
[] |
no_license
|
require 'gilded_rose'
describe GildedRose do
describe '#update_quality' do
it 'updates the quality of different items' do
normal = Normal.new('Normal', 5, 5)
sulfur = Sulfuras.new('Sulfuras, Hand of Ragnaros', 10, 5)
brie = Brie.new('Aged Brie', 9, 8)
ticket = Ticket.new('Backstage passes to a TAFKAL80ETC concert', 6, 8)
conjured = Conjured.new('Conjured', 9, 8)
rose = GildedRose.new([normal, sulfur, brie, conjured, ticket])
updated = rose.update_quality
expect(updated[0].sell_in).to eq 4
expect(updated[0].quality).to eq 4
expect(updated[1].sell_in).to eq 10
expect(updated[1].quality).to eq 5
expect(updated[2].sell_in).to eq 8
expect(updated[2].quality).to eq 9
expect(updated[3].sell_in).to eq 8
expect(updated[3].quality).to eq 6
expect(updated[4].sell_in).to eq 5
expect(updated[4].quality).to eq 11
end
end
end
| true |
1eb0954e93538c6940436c14e7474a74c1286b3e
|
Ruby
|
johnnyt/maglev-presentation
|
/models/player.rb
|
UTF-8
| 763 | 2.828125 | 3 |
[] |
no_license
|
class Transition
attr_accessor :player, :cell, :time
def self.store
@store ||= IdentitySet.new
end
def initialize(player, cell, time=Time.now)
@player, @cell, @time = player, cell, time
self.class.store.add self
end
end
class Player
attr_accessor :name, :transitions, :current_cell
def self.store
@store ||= IdentitySet.new
end
def initialize(name)
@name = name
@transitions = []
move_to GeoCell.root
self.class.store.add self
end
def move_to(cell)
current_cell.remove_content(self) if current_cell
add_transition cell
self.current_cell = cell
cell.add_content self
end
def add_transition(cell)
transitions << Transition.new(self, cell)
end
end
Transition.store
Player.store
| true |
7aceb043833b088d05f67bc3dc8b37974efbc3ec
|
Ruby
|
ivaverka/Learn-Ruby-the-Hard-Way
|
/questions.rb
|
UTF-8
| 1,076 | 3.546875 | 4 |
[] |
no_license
|
module Questions # I need to think how to make it ask a question check the answer (done) and then GO TO THE RIGHT ROOM BASED ON THE ANSWER.
# SHould I put the logic in the Scene Class and use super in other classes or Should I put the Logic inside this module?
# Because now it will only iterate over keys and values and it will go to 'death' only when the answer is wrong.
# !!!Should I put in my class this module and logic: if answer is right, go to the next room?
# Do I need this module at all? What if I put @@questions into the Map class, next_question - within each class?
@@questions = {
'WHAT IS A VARIABLE' => "a name for something",
'WHAT IS AN ARRAY' => "a collection of something",
}
def Questions.next_question(question_name)
#puts "ASKING QUESTION"
@@questions.each_key do |key|
puts "My question is #{key} >>"
answer = $stdin.gets.chomp
if answer == @@questions[key] # I am not sure how/why it is working but it is working :-)
puts "This answer is right"
else
puts "Wrong"
return 'death'
end
end
end
end
| true |
d973ded977d5edbd24a177ddd86be41adcdb9e1d
|
Ruby
|
gengogo5/atcoder
|
/ABC/abc222/ABC222_A.rb
|
UTF-8
| 35 | 2.59375 | 3 |
[] |
no_license
|
N = gets.to_i
printf("%04d\n", N)
| true |
320574f16e0074f2a36e13c91f5ce2fc93898017
|
Ruby
|
Gowdhamselvam/Basics-of-Ruby
|
/foreach.rb
|
UTF-8
| 45 | 2.671875 | 3 |
[] |
no_license
|
IO.foreach("input.txt") {|block| puts block}
| true |
3b9f276d86b746036e75f7fb39aa995eb3d14d4c
|
Ruby
|
NatasaPetrovic/railsCourse
|
/ruby_projects/hash.rb
|
UTF-8
| 454 | 3.453125 | 3 |
[] |
no_license
|
# Hash
my_details = {'name' => 'nata', 'favcolor' => 'red'}
puts my_details['favcolor']
myhash = {a: 1, b: 2, c: 3}
puts myhash[:c]
myhash[:d] = 7
puts myhash[:d]
puts myhash
myhash[:name] = "Nata"
puts myhash[:name]
myhash.delete(:d)
numbers = {a: 1, b: 2, c: 3, d: 4 }
numbers.each {|k, v| puts v}
numbers.each {|k, v| puts "Key: #{k}, value: #{v}"}
numbers.each {|k, v| numbers.delete(k) if v>3}
puts numbers
puts numbers.select {|k,v| v.odd?}
| true |
5f27b86cd37f01cbfb51741857ee1b20635dfed9
|
Ruby
|
emmiehayes/scrabble_api
|
/app/models/word.rb
|
UTF-8
| 925 | 2.734375 | 3 |
[] |
no_license
|
class Word
def initialize(word)
@word = word
end
def validate
return "'#{@word}' is not a valid word." if response.status == 404
return "'#{word_id}' is a valid word and its root form is '#{root_word}'." if dictionary_data.first[:id] == @word
end
private
def root_word
dictionary_data.first[:lexicalEntries][0][:inflectionOf][0][:text]
end
def dictionary_data
JSON.parse(response.body, symbolize_names: true)[:results]
end
def response
conn.get("/api/v1/inflections/#{source_lang}/#{word_id}")
end
def conn
Faraday.new(url: "https://od-api.oxforddictionaries.com") do |faraday|
faraday.headers["accept"] = 'application/json'
faraday.headers["app_id"] = ENV['app_id']
faraday.headers["app_key"] = ENV['app_key']
faraday.adapter Faraday.default_adapter
end
end
def source_lang
'en'
end
def word_id
@word
end
end
| true |
b747270c71849a2b71ea6df309e3e373b8b26161
|
Ruby
|
orderedlist/mongomapper
|
/lib/mongo_mapper/observing.rb
|
UTF-8
| 1,100 | 2.765625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'observer'
require 'singleton'
require 'set'
module MongoMapper
module Observing #:nodoc:
def self.included(model)
model.class_eval do
extend Observable
end
end
end
class Observer
include Singleton
class << self
def observe(*models)
models.flatten!
models.collect! { |model| model.is_a?(Symbol) ? model.to_s.camelize.constantize : model }
define_method(:observed_classes) { Set.new(models) }
end
def observed_class
if observed_class_name = name[/(.*)Observer/, 1]
observed_class_name.constantize
else
nil
end
end
end
def initialize
Set.new(observed_classes).each { |klass| add_observer! klass }
end
def update(observed_method, object) #:nodoc:
send(observed_method, object) if respond_to?(observed_method)
end
protected
def observed_classes
Set.new([self.class.observed_class].compact.flatten)
end
def add_observer!(klass)
klass.add_observer(self)
end
end
end
| true |
de5ccc30574870b1abebc32d8f5946149f5c1718
|
Ruby
|
saidmaadan/mks
|
/Ruby/project-euler/problem31.rb
|
UTF-8
| 648 | 3.90625 | 4 |
[] |
no_license
|
# In England the currency is made up of pound, £, and pence, p, and there are
# eight coins in general circulation:
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
# It is possible to make £2 in the following way:
# 1£1 + 150p + 220p + 15p + 12p + 31p
# How many different ways can £2 be made using any number of coins?
#
count = 0
200.step(0, -200) do |a|
a.step(0, -100) do |b|
b.step(0, -50) do |c|
c.step(0, -20) do |d|
d.step(0, -10) do |e|
e.step(0, -5) do |f|
f.step(0, -2) do
count += 1
end
end
end
end
end
end
end
puts count
| true |
0c0d774585de510db9edb57e9944b9466799bb74
|
Ruby
|
Fitog4/rvnb
|
/app/models/booking_request.rb
|
UTF-8
| 570 | 2.53125 | 3 |
[] |
no_license
|
class BookingRequest < ApplicationRecord
belongs_to :rv
belongs_to :user
validates :status, inclusion: { in: ['pending', 'approved', 'paid'] }
validates :location, :date_from, :date_till, presence: true
validate :valid_dates?
private
def valid_dates?
# date_till >= date_from >= Date.today
unless date_till >= date_from
errors.add(:date_till, 'Booking end date must be after booking start date')
end
unless date_from >= Date.today
errors.add(:date_from, 'Booking start date must be today or in the future')
end
end
end
| true |
5d088c7a5d9fe198b1008896b65e1a44b88661a6
|
Ruby
|
mikey-roberts/mini_projects
|
/sub_string/sub_string.rb
|
UTF-8
| 466 | 3 | 3 |
[] |
no_license
|
dictionary = ["plastic","previous","below","low","aggressive","cautious", "truculent","full","accessible","material","amused","selfish","apathetic","perpetual"]
# takes a string input and returns a hash. K - string V - number of entires
def sub_string(string, dictionary)
string = string.downcase.split(" ")
merge = string += dictionary
result = {}
merge.tally.delete_if {|key, val| val <= 1 }.each { |k, v| result[k] = v - 1 }
result
end
| true |
f0619bff0b07201493404efe9d70ab92a28aeaa0
|
Ruby
|
sekoudosso82/Ruby_essential
|
/testing/spec/palindrome_checker_spec.rb
|
UTF-8
| 1,079 | 2.84375 | 3 |
[] |
no_license
|
require_relative '../lib/palindrome_cheker'
RSpec.describe PalindromeChecker do
describe '#check' do
let(:checker) {PalindromeChecker.new}
it 'returns true when given a palaindrome' do
word = "racecar"
result = checker.check(word)
expect(result).to be true
end
it 'returns false when word is not a palaindrome' do
word = 'not_a_palaindrome'
result = checker.check(word)
expect(result).to be false
end
it 'returns true when given a palaindrome with space' do
word = 'taco cat'
result = checker.check(word)
expect(result).to be true
end
it 'returns true when given a palaindrome of mixed case' do
word = 'NeverOddOrEven'
result = checker.check(word)
expect(result).to be true
end
# pending case to be write
xit 'return true when given a palindrome with snake case'
xit 'other thing'
xit 'something else'
end
end
| true |
e40b6e62ff78555b1b005bcda9dd5ce795b891ae
|
Ruby
|
alexdaesikkim/hcef
|
/app/models/guardian.rb
|
UTF-8
| 742 | 2.640625 | 3 |
[] |
no_license
|
class Guardian < ActiveRecord::Base
#add date of birth to uniquely identify
#relationships
has_many :children
has_many :guardian_locations
has_many :locations, through: :guardian_locations
#validations
validates_presence_of :first_name, :last_name, :phone, :email
validates_date :date_of_birth, :before => lambda { Date.today }, on: :create
validates_format_of :phone, with: /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-. ]\d{4})\z/, message: "should be 10 digits"
validates_format_of :email, with: /\A[\w]([^@\s,;]+)@(([\w-]+\.)+(com|edu|org|net|gov|mil|biz|info))\z/i, message: "is not a valid format"
#scopes
scope :alphabetical, -> { order('last_name', 'first_name')}
#methods
def name
"#{first_name} #{last_name}"
end
end
| true |
28a339624ea7a8c113d047abcf20b403313a060c
|
Ruby
|
ktmishra1-appdev/loops-chapter
|
/spec/scripts/loops_spec.rb
|
UTF-8
| 4,594 | 3.109375 | 3 |
[] |
no_license
|
describe "loops_fizz_buzz.rb" do
it "should output the correct response", points: 1 do
# Un-require loops_fizz_buzz.rb
loops_fizz_buzz = $".select{|r| r.include? 'loops_fizz_buzz.rb'}
$".delete(loops_fizz_buzz.first)
response = File.read("spec/support/fizz_buzz.txt")
expect { require_relative("../../loops_fizz_buzz") }.to output(/1\n2\n"?Fizz"?\n4\n"?Buzz"?\n"?Fizz"?\n7\n8\n"?Fizz"?\n"?Buzz"?\n11\n"?Fizz"?\n13\n14\n"?FizzBuzz"?\n16\n17\n"?Fizz"?\n19\n"?Buzz"?\n"?Fizz"?\n22\n23\n"?Fizz"?\n"?Buzz"?\n26\n"?Fizz"?\n28\n29\n"?FizzBuzz"?\n31\n32\n"?Fizz"?\n34\n"?Buzz"?\n"?Fizz"?\n37\n38\n"?Fizz"?\n"?Buzz"?\n41\n"?Fizz"?\n43\n44\n"?FizzBuzz"?\n46\n47\n"?Fizz"?\n49\n"?Buzz"?\n"?Fizz"?\n52\n53\n"?Fizz"?\n"?Buzz"?\n56\n"?Fizz"?\n58\n59\n"?FizzBuzz"?\n61\n62\n"?Fizz"?\n64\n"?Buzz"?\n"?Fizz"?\n67\n68\n"?Fizz"?\n"?Buzz"?\n71\n"?Fizz"?\n73\n74\n"?FizzBuzz"?\n76\n77\n"?Fizz"?\n79\n"?Buzz"?\n"?Fizz"?\n82\n83\n"?Fizz"?\n"?Buzz"?\n86\n"?Fizz"?\n88\n89\n"?FizzBuzz"?\n91\n92\n"?Fizz"?\n94\n"?Buzz"?\n"?Fizz"?\n97\n98\n"?Fizz"?\n"?Buzz"?/).to_stdout
end
end
describe "loops_letter_count.rb" do
it "should count 1 to 6 with the input of 'banana'", points: 1 do
# Un-require loops_letter_count.rb
loops_letter_count = $".select{|r| r.include? 'loops_letter_count.rb'}
$".delete(loops_letter_count.first)
allow_any_instance_of(Object).to receive(:gets).and_return("banana")
response = /1\n2\n3\n4\n5\n6\n.*banana is 6 letters long/
expect { require_relative("../../loops_letter_count") }.to output(response).to_stdout
end
end
describe "loops_letter_count.rb" do
it "should count 1 to 15 with the input of 'fantasmagorical'", points: 1 do
# Un-require loops_letter_count.rb
loops_letter_count = $".select{|r| r.include? 'loops_letter_count.rb'}
$".delete(loops_letter_count.first)
allow_any_instance_of(Object).to receive(:gets).and_return("fantasmagorical")
response = /1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n.*fantasmagorical is 15 letters long/
expect { require_relative("../../loops_letter_count") }.to output(response).to_stdout
end
end
describe "loops_letter_count.rb" do
it "should count 1 with the input of 'a'", points: 1 do
# Un-require loops_letter_count.rb
loops_letter_count = $".select{|r| r.include? 'loops_letter_count.rb'}
$".delete(loops_letter_count.first)
allow_any_instance_of(Object).to receive(:gets).and_return("a")
response = /1\n.*a is 1 letters long/
expect { require_relative("../../loops_letter_count") }.to output(response).to_stdout
end
end
describe "loops_stop.rb" do
it "should count 1 with the input of 'a'", points: 1 do
# Un-require loops_letter_count.rb
loops_letter_count = $".select{|r| r.include? 'loops_letter_count.rb'}
$".delete(loops_letter_count.first)
allow_any_instance_of(Object).to receive(:gets).and_return("a")
response = /1\n.*a is 1 letters long/
expect { require_relative("../../loops_letter_count") }.to output(response).to_stdout
end
end
describe "loops_multiples.rb" do
it "should print the correct multiples from 1 to 10 with the input of '2'", points: 1 do
# Un-require loops_letter_count.rb
loops_multiples = $".select{|r| r.include? 'loops_multiples.rb'}
$".delete(loops_multiples.first)
allow_any_instance_of(Object).to receive(:gets).and_return("2")
response = /2\n4\n6\n8\n10\n12\n14\n16\n18\n20/
expect { require_relative("../../loops_multiples") }.to output(response).to_stdout
end
end
describe "loops_multiples.rb" do
it "should print the correct multiples from 1 to 10 with the input of '3'", points: 1 do
# Un-require loops_letter_count.rb
loops_multiples = $".select{|r| r.include? 'loops_multiples.rb'}
$".delete(loops_multiples.first)
allow_any_instance_of(Object).to receive(:gets).and_return("3")
response = /3\n6\n9\n12\n15\n18\n21\n24\n27\n30/
expect { require_relative("../../loops_multiples") }.to output(response).to_stdout
end
end
describe "loops_multiples.rb" do
it "should print the correct multiples from 1 to 10 with the input of '0'", points: 1 do
# Un-require loops_letter_count.rb
loops_multiples = $".select{|r| r.include? 'loops_multiples.rb'}
$".delete(loops_multiples.first)
allow_any_instance_of(Object).to receive(:gets).and_return("0")
response = /0\n0\n0\n0\n0\n0\n0\n0\n0\n0/
expect { require_relative("../../loops_multiples") }.to output(response).to_stdout
end
end
| true |
d83748d802f2febcadb2b5ad0d74d7f730cd2371
|
Ruby
|
cyberarm/visual_plotter
|
/lib/machine/compiler/processor.rb
|
UTF-8
| 965 | 2.78125 | 3 |
[] |
no_license
|
class Machine
class Compiler
Node = Struct.new(:x, :y)
class Processor
def initialize(compiler:, canvas:, mode: :default)
@compiler = compiler
@canvas = canvas
case mode
when :classic, :default
default
when :graph_search
graph_search
when :generational
generational
else
raise "Unknown Processor Mode: #{mode}"
end
end
def default
solver = ClassicSolver.new(canvas: @canvas)
@compiler.events << solver.path_events
@compiler.events.flatten!
end
def graph_search
solver = GraphSearchSolver.new(canvas: @canvas)
@compiler.events << solver.path_events
@compiler.events.flatten!
end
def generational
solver = Generational.new(canvas: @canvas)
@compiler.events << solver.path_events
@compiler.events.flatten!
end
end
end
end
| true |
f9de4a618f7277de466618e213ca22800371a93a
|
Ruby
|
sokampdx/head_first_design_patterns
|
/ruby/PizzaStore/pizza_store_simple.rb
|
UTF-8
| 2,024 | 3.890625 | 4 |
[] |
no_license
|
class SimplePizzaFactory
def create(type)
case type
when 'cheese'
CheesePizza.new
when 'pepperoni'
PepperoniPizza.new
when 'clam'
ClamPizza.new
when 'veggie'
VeggiePizza.new
end
end
end
class PizzaStore
def initialize(factory)
@factory = factory
end
def order(type)
pizza = @factory.create(type)
pizza.prepare
pizza.bake
pizza.cut
pizza.box
pizza
end
end
class Pizza
attr_accessor :name
def initialize
@toppings = []
end
def name
@name
end
def prepare
puts "Preparing #{@name}"
puts "Tossing #{@dough} ..."
puts "Adding #{@sauce} ..."
print "Adding topping:"
@toppings.each { |topping| print " #{topping}" }
puts
end
def bake
puts "Bake for 25mins at 350°"
end
def cut
puts "Cutting pizza into diagonal shapes"
end
def box
puts "Place pizza in official Pizza Store box"
end
end
class CheesePizza < Pizza
def initialize
super
@name = 'Cheese Pizza'
@dough = 'Thin cut dough'
@sauce = 'Marinara sauce'
@toppings << 'Grated Reggiano Cheese'
end
end
class PepperoniPizza < Pizza
def initialize
super
@name = 'Pepperoni Pizza'
@dough = 'Thin cut dough'
@sauce = 'Marinara sauce'
@toppings << 'Sliced Pepperoni'
end
end
class ClamPizza < Pizza
def initialize
super
@name = 'Clam Pizza'
@dough = 'Thin cut dough'
@sauce = 'Clam sauce'
@toppings << 'Clam'
end
end
class VeggiePizza < Pizza
def initialize
super
@name = 'Veggie Pizza'
@dough = 'Thin cut dough'
@sauce = 'Marinara sauce'
@toppings << 'Pineapplie' << 'Mushroom' << 'Bell Pepper'
end
end
def main
factory = SimplePizzaFactory.new
pizza_store = PizzaStore.new(factory)
pizza = pizza_store.order('cheese')
puts pizza.name
pizza = pizza_store.order('pepperoni')
puts pizza.name
pizza = pizza_store.order('clam')
puts pizza.name
pizza = pizza_store.order('veggie')
puts pizza.name
end
main if __FILE__ == $0
| true |
03df5447d6e0c0558f54e5070a7d8553deebd59f
|
Ruby
|
Green-stripes/reverse-each-word-001-prework-web
|
/reverse_each_word.rb
|
UTF-8
| 121 | 3.296875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def reverse_each_word(phrase)
hold = []
phrase.split(" ").each do |x|
hold << x.reverse
end
hold.join(" ")
end
| true |
2e85f6e0c33f915299092af7bf2c0eed7760c71e
|
Ruby
|
pmarshall17/ruby_calculator
|
/calculator.rb
|
UTF-8
| 1,081 | 4.125 | 4 |
[] |
no_license
|
def add
print "Enter number 1: "
@a1 = gets.chomp.to_i
print "Enter number 2 : "
@a2 = gets.chomp.to_i
puts "Calculating... #{@a1 + @a2}"
end
def subtract
print "Enter number 1: "
@s1 = gets.chomp.to_i
print "Enter number 2: "
@s2 = gets.chomp.to_i
puts "Calculating... #{@s1 - @s2}"
end
def multiply
print "Enter number 1: "
@m1 = gets.chomp.to_i
print "Enter number 2: "
@m2 = gets.chomp.to_i
puts "Calculating... #{@m1 * @m2}"
end
def divide
print "Enter number 1: "
@d1 = gets.chomp.to_i
print "Enter number 2: "
@d2 = gets.chomp.to_i
puts "Calculating... #{@d1 / @d2}"
end
def menu
puts "*** Welcome to the ruby calculator ***"
puts "To exit program at any time: press 'q'"
puts "Will we add, subtract, divide or multiply today?"
operator_response = gets.chomp.to_s
if operator_response == "add"
add
end
if operator_response == "subtract"
subtract
end
if operator_response == "multiply"
multiply
end
if operator_response == "divide"
divide
end
if operator_response == "q"
exit
end
end
while true
menu
end
| true |
b6805960831fb25694b33757ab19c9c513593f79
|
Ruby
|
pawelduda/codeeval-ruby-solutions
|
/easy/3.rb
|
UTF-8
| 246 | 3.515625 | 4 |
[] |
no_license
|
# https://www.codeeval.com/browse/3/
require 'prime'
def is_palindrome?(str)
str == str.reverse
end
def largest_prime
(1..1000).reverse_each do |x|
if x.prime?
return x if is_palindrome?(x.to_s)
end
end
end
p largest_prime
| true |
03cfdfa3b94be2e19f83045c7d5d3990a845c02d
|
Ruby
|
JustSilverman/xDBC-todo_list_with_ar
|
/app/controllers/todo_controller.rb
|
UTF-8
| 1,103 | 2.609375 | 3 |
[] |
no_license
|
require_relative '../models/list_item'
require_relative '../views/todo_view'
class TodoController
attr_reader :id, :action, :task, :user_interface
def initialize(args)
@id = args[:id].to_i
@action = args[:action]
@task = args[:task]
@user_interface = TodoView.new
execute!
end
def execute!
if self.respond_to?(action.to_sym)
unless self.send(action.to_sym)
user_interface.invalid_id
end
else
user_interface.non_action
end
end
def default_task_args
{"id" => id, "task" => task, "completed_at" => nil}
end
def add
item = ListItem.create!(default_task_args)
user_interface.confirm_add(item)
true
end
def list
user_interface.display_list(ListItem.all)
end
def delete
item = ListItem.all[id-1]
return false if item.nil?
user_interface.confirm_delete(item)
item.destroy
true
end
def complete
item = ListItem.all[id-1]
return false if item.nil?
item.complete!
user_interface.confirm_complete(item)
true
end
end
| true |
279801053729847a8e0d15d3c18a9a07e86edf2d
|
Ruby
|
chuckremes/rzmq_brokers
|
/lib/rzmq_brokers/broker/worker.rb
|
UTF-8
| 3,735 | 2.609375 | 3 |
[] |
no_license
|
module RzmqBrokers
module Broker
# Used by the Broker to track the state of a connected Worker and maintain heartbeats
# between itself and the actual Worker.
#
class Worker
attr_reader :service_name, :identity, :envelope
def initialize(reactor, handler, service_name, identity, heartbeat_interval, heartbeat_retries, envelope)
@reactor = reactor
@handler = handler
@service_name = service_name
@identity = identity
@envelope = envelope.dup
@heartbeat_interval = heartbeat_interval
@heartbeat_retries = heartbeat_retries
@hb_sent_at = Time.at(0) # set to epoch so first heartbeat goes out
start_heartbeat
@hb_received_at = Time.now # true because we just received a READY msg
end
def return_address
@envelope.map { |address| ZMQ::Message.new(address) }
end
def format_request(request)
# reset hb_sent_at so that we consider any message (including a request) to be a
# heartbeat; this prevents us from "overbeating" and wasting bandwidth
@hb_sent_at = Time.now
return_address + request.to_msgs
end
def start_heartbeat
@reactor.log(:debug, "#{self.class}, Worker [#{@identity}] for service [#{@service_name}] starting heartbeat with interval [#{@heartbeat_interval}] for reactor [#{@reactor.name}] on thread [#{Thread.current['reactor-name']}]")
@dead = false
@heartbeat_timer = @reactor.periodical_timer(@heartbeat_interval) { beat }
end
def beat
now = Time.now
elapsed = (now - @hb_sent_at) * 1_000 # convert to milliseconds so we are comparing the same "units"
if elapsed >= @heartbeat_interval
@hb_sent_at = now
@reactor.log(:debug, "#{self.class}, Worker [#{@identity}] for service [#{@service_name}] is sending a HB to the worker.")
@handler.send_worker_heartbeat(self)
@reactor.log(:warn, "#{self.class}, Worker [#{@identity}] is dead for service [#{@service_name}] but the broker is still sending heartbeats! Make sure this object is only ever accessed from its own reactor thread!") if @dead
end
end
# Called by handler whenever it receives a worker heartbeat.
#
def process_heartbeat(message = nil)
@reactor.log(:debug, "#{self.class}, On broker, worker [#{@identity}] for service [#{@service_name}] received a HB message.")
@hb_received_at = Time.now
end
# Called when the worker has sent a DISCONNECT or its heartbeats have timed out.
#
def die
@reactor.log(:info, "#{self.class}, Worker [#{@identity}] for service [#{@service_name}] is exiting.")
canceled = @heartbeat_timer.cancel
unless canceled
@reactor.log(:error, "#{self.class}, Worker [#{@identity}] for service [#{@service_name}] could *not* cancel heartbeat timer on reactor [#{@reactor.name}]. There must be a threading problem somewhere. Make sure this object is *only accessed* from its reactor thread!")
end
@dead = true
end
# True when this worker reference hasn't received a heartbeat from its worker
# in interval*retries time.
#
def expired?
# convert time to milliseconds so this comparison works correctly
elapsed = ((Time.now - @hb_received_at) * 1_000)
if elapsed > (@heartbeat_interval * @heartbeat_retries)
@reactor.log(:warn, "#{self.class}, Broker Worker [#{@identity}] for service [#{@service_name}] is expiring, last received hb at #{@hb_received_at}")
true
else
false
end
end
end # Worker
end
end
| true |
21eae3507b98a1c76fbf0753f323eab7e58fb220
|
Ruby
|
opfo/resources
|
/scripts/db_parser.rb
|
UTF-8
| 6,699 | 3.140625 | 3 |
[] |
no_license
|
# Used to parse tags from a stackoverflow database
require 'colorize'
require 'debugger'
unless File.exists? "./so.sqlite"
puts "=============================================================================".red
puts "ERROR ==> script cannot execute without the original db in the same directory"
puts ""
puts "FIX ==> Make sure that the original db is in this dictory and is named so.sqlite"
puts "=============================================================================".red
abort
end
require 'sqlite3'
TAGS_ROW = 16
AUX_DB = "./auxiliary.sqlite"
# Remove the current auxiliary database
File.delete AUX_DB if File.exists? AUX_DB
sourceDB = SQLite3::Database.new("./so.sqlite")
destinationDB = SQLite3::Database.new(AUX_DB)
# Convenience methods
def tokenize_string(string)
string.scan /<([^<>]+)>/
end
def get_pair(db, one, other)
db.execute("SELECT * FROM tag_frequencies WHERE first_tag = '#{one}' AND second_tag = '#{other}'")
end
def insert_pair(db, one, other)
db.execute("INSERT INTO tag_frequencies VALUES('#{one}','#{other}', 1)")
end
def set_pair(db, one, other, n)
db.execute("UPDATE tag_frequencies SET counter=#{n} WHERE first_tag = '#{one}' AND second_tag = '#{other}'")
end
# Creates a hash column_name => column_index
# ["apa", "bepa", "cepa"]
# => {"apa": 0, "bepa": 1, "cepa": 2}
def parse_columns(columns)
columns_hash = {}
columns.each_with_index do |column, i|
columns_hash[column] = i
end
columns_hash
end
# Create tags table
puts "Create tables tags and tag_frequencies".green
destinationDB.execute("CREATE TABLE tags(id INTEGER PRIMARY KEY, name TEXT, counter INTEGER)")
destinationDB.execute("CREATE TABLE tag_frequencies(first_tag TEXT, second_tag TEXT, counter INTEGER)")
# Select all posts with tags
puts "Read tags from source db".green
rows = sourceDB.execute("SELECT * FROM posts WHERE tags <> 'NULL'")
tags = {}
tag_frequencies = {}
rows.each do |row|
# Each row is an array of attributes, we happen to know that tags is column 16
raw_tags = row[TAGS_ROW]
parsed_tags = tokenize_string(raw_tags)
parsed_tags.each do |tag|
if tags.has_key? tag
tags[tag] += 1
else
tags[tag] = 1
end
end
parsed_tags.combination(2).to_a.each do |pair|
# For each combination, increment the frequency table
flattened = pair.flatten.sort
key = [flattened[0], flattened[1]]
if tag_frequencies.has_key? key
tag_frequencies[key] += 1
else
tag_frequencies[key] = 1
end
# existing = get_pair(destinationDB, flattened[0], flattened[1])
# if existing.empty?
# insert_pair(destinationDB, flattened[0], flattened[1])
# else
# set_pair(destinationDB, flattened[0], flattened[1], existing.first[2].to_i + 1)
# end
end
end
# Create tags
puts "Write tags to aux DB".green
tags_write_query = "INSERT INTO tags (name, counter) VALUES(?,?)"
queries = []
tags.each do |tag, frequency|
queries.push [tag, frequency]
end
queries.each {|args| destinationDB.execute(tags_write_query, args)}
# Create tag frequencies
puts "Write tag frequencies to aux DB".green
tag_frequency_write_query = "INSERT INTO tag_frequencies(first_tag, second_tag, counter) VALUES (?,?,?)"
tag_frequencies.each do |pair, value|
destinationDB.execute(tag_frequency_write_query, [pair[0], pair[1], value])
end
####
## Create the Full Text Search indexes
####
#### Posts
puts "Create posts index".green
destinationDB.execute("CREATE VIRTUAL TABLE posts_index USING fts4(object_id, main_index_string, aux_index_string, tags)")
posts_select_query =
%Q(
SELECT "posts"."id", "posts"."body", "posts"."title", "users"."display_name", "posts"."tags"
FROM "users", "posts"
WHERE "posts"."owner_user_id" = "users"."id"
)
answers_select_query =
%Q(
SELECT "posts"."id", "posts"."parent_id", "posts"."body", "posts"."title"
FROM "posts"
WHERE "posts"."post_type_id" = 2
)
columns = nil
index_queries = {}
index_query_prototype = "INSERT INTO posts_index(object_id, main_index_string, aux_index_string, tags) VALUES(?, ?, ?, ?)"
puts "Gather all posts data".green
sourceDB.execute2(posts_select_query) do |row|
if columns == nil
columns = parse_columns(row)
else
owner_display_name = row[columns["display_name"]]
body = row[columns["body"]]
title = row[columns["title"]]
id = row[columns["id"]]
tags = tokenize_string(row[columns["tags"]]).join(" ")
main_index_string = "#{body} #{title} #{owner_display_name}".gsub(/<([^<>]+)>/, "")
index_queries[id] = [id, main_index_string, "", tags]
end
end
puts "Gather answer data".green
columns = nil
sourceDB.execute2(answers_select_query) do |row|
if columns == nil
columns = parse_columns(row)
else
parent_id = row[columns["parent_id"]]
body = row[columns["body"]]
title = row[columns["title"]]
index_string = " #{body} #{title}".gsub(/<([^<>]+)>/, "")
question_query = index_queries[parent_id]
if question_query
current_answer_string = question_query[2]
current_answer_string ||= ""
question_query[2] = current_answer_string + index_string
end
end
end
index_queries.each do |id, query|
begin
destinationDB.execute(index_query_prototype, query)
rescue Exception => ex
puts ex.message.red
end
end
#### Users
puts "Create users index".green
destinationDB.execute("CREATE VIRTUAL TABLE users_index USING fts4(object_id, index_string)")
users_select_query = %Q(SELECT "users"."id", "users"."display_name" FROM "users")
user_index_query_prototype = "INSERT INTO users_index(object_id, index_string) VALUES(?, ?)"
puts "Gather user data".green
user_index_queries = []
columns = nil
sourceDB.execute2(users_select_query) do |row|
if columns.nil?
columns = parse_columns(row)
else
user_id = row[columns["id"]]
display_name = row[columns["display_name"]]
user_index_queries << [user_id, display_name]
end
end
puts "Write user data".green
user_index_queries.each do |query|
begin
destinationDB.execute(user_index_query_prototype, query)
rescue Exception => ex
puts ex.message.red
end
end
#### Create users_votes
puts "Create users_votes".green
users_votes_query = %Q{
CREATE TABLE "users_votes" (
"user_id" integer,
"post_id" integer,
"upvote" integer,
PRIMARY KEY("user_id","post_id")
)
}
destinationDB.execute(users_votes_query)
#### Create comments_votes
puts "Create comments_votes".green
comments_votes_query = %Q{
CREATE TABLE "comments_votes" (
"comment_id" integer,
"user_id" integer,
PRIMARY KEY("user_id", "comment_id")
)
}
destinationDB.execute(comments_votes_query)
puts "Done".green
| true |
ba8064fa43647f4d89bb6b729775c45e097176ad
|
Ruby
|
ksashikumar/bootcamp-ruby
|
/Polynomials/polynomials.rb
|
UTF-8
| 762 | 3.390625 | 3 |
[] |
no_license
|
class Polynomials
def initialize(array)
@array = array
@length = @array.length()-1
@result = ""
end
def compute
raise ArgumentError, "Need atleast 2 coefficients" if @length < 1
@array.each do |coeff|
if coeff != '0'
if coeff > '0'
if @length != @array.length() - 1
@result += '+'
end
@result += coeff if coeff != '1' || @length == 0
else
coeff != '-1' || @length == 0 ? @result += coeff : @result += '-'
end
if @length >= 2
@result += "x^#{@length}"
elsif @length == 1
@result += 'x'
end
end
@length = @length - 1
end
return @result
end
end
| true |
20100b52bfaf4d8cff612e787dbab2a95bf93de6
|
Ruby
|
marcelosnts/estudos_ruby
|
/Modulos/app2.rb
|
UTF-8
| 105 | 2.59375 | 3 |
[] |
no_license
|
require_relative "mixin"
var = Mixin.new
puts var.a1
puts var.a2
puts var.b1
puts var.b2
puts var.ex1
| true |
e7c32483f18d155a3d203d3fd84a43077cab9ee5
|
Ruby
|
34code/Hello-Ruby
|
/RubyPickaxe/Chapter 2 - Ruby.new/hashes.rb
|
UTF-8
| 600 | 3.75 | 4 |
[
"MIT",
"BSD-3-Clause",
"BSD-4-Clause",
"BSD-2-Clause"
] |
permissive
|
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
p h.length
p h['dog']
h['cow'] = 'bovine'
h[12] = 'dodecine'
h['cat'] = 99
p h
def words_from_string(string)
string.downcase.scan(/[\w']+/)
end
p words_from_string("But I didn't inhale, he said (emphatically)...")
def count_frequency(word_list)
counts = Hash.new(0)
for word in word_list
counts[word] += 1
end
counts
end
raw_text = File.read("para.txt")
words_list = words_from_string(raw_text)
counts = count_frequency(words_list)
sorted = counts.sort_by {|word, count| count}
top_5 = sorted.last(5)
p top_5
| true |
59dc41c2ceb01e6786e3a5f285c794becb3a646f
|
Ruby
|
LynnAmsbury/hayk-assessment-build-classes-and-objects
|
/Building.rb
|
UTF-8
| 893 | 3.375 | 3 |
[] |
no_license
|
# frozen_string_literal: true
class Building
attr_accessor :name, :number_of_tenants
attr_reader :address
@@all = []
def initialize(name, address, number_of_floors = 0, number_of_tenants = 0)
@name = name
@address = address
@number_of_floors = number_of_floors
@number_of_tenants = number_of_tenants
@@all << self
end
def self.all
@@all
end
def self.tenant_average
total_tenants = @@all.reduce(0) do |tenant_count, building|
tenant_count += building.number_of_tenants
end
total_tenants / @@all.count
end
def self.placards
@@all.map(&:placard)
# @@all.map do |building|
# building.placard # building is an INSTANCE, so we can call instance methods on it
# end
end
def placard
"#{@name}: #{@address}"
end
def average_tenants_per_floor
@number_of_tenants / @number_of_floors.to_f
end
end
| true |
08b6103abff18adb7be9a9b4b91434cb81779c29
|
Ruby
|
rminasi/hangman-rails-ruby
|
/app/models/guess_bot.rb
|
UTF-8
| 1,926 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
class GuessBot
class << self
def calculate_guesses(word)
# Loop through single letters in order of frequency until we get a match
# TODO: Loop through bigrams trying letters in order of frequency
letters_guessed = word.chars.map { |letter| [letter.downcase, false] }.to_h
letters_guessed.default = false
guess_candidates = LetterFrequencyAnalysis.letters_by_frequency
guess_attempts = []
until word_guessed?(letters_guessed) || possibles_exhausted(guess_attempts)
guess_candidates = reject_previous_attempts(guess_candidates, guess_attempts)
attempts = next_guesses(guess_candidates, letters_guessed)
correct_guesses = attempts & letters_guessed.keys
correct_guesses.each { |guess| letters_guessed[guess] = true }
# Stop unbounded loop exection - we should always get more attempts in each loop
loop_check = guess_attempts.length
guess_attempts.concat(attempts).uniq!
raise "No additional attempts found" if loop_check == guess_attempts.length
end
guess_attempts
end
private
def word_guessed?(letters_guessed)
letters_guessed.all? { |letter, guessed| guessed }
end
def possibles_exhausted(guess_attempts)
possibles = ('a'..'z').to_a - guess_attempts
possibles.empty?
end
def reject_previous_attempts(guess_candidates, guess_attempts)
guess_candidates.reject { |candidate| guess_attempts.include?(candidate) }
end
def next_guesses(guess_candidates, letters_guessed)
first_correct_guess = guess_candidates.find_index do |letter|
!letters_guessed[letter] && letters_guessed.keys.include?(letter)
end
if first_correct_guess.nil?
first_correct_guess = guess_candidates.length
else
first_correct_guess += 1
end
guess_candidates.slice(0, first_correct_guess)
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.