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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2e7b6c7e15d0be6ea578b50d807841e794e8cd04 | Ruby | vdk88/seek | /lib/seek/bio_schema/csv_reader.rb | UTF-8 | 726 | 2.75 | 3 | [
"BSD-3-Clause",
"JSON"
] | permissive | module Seek
module BioSchema
# Reads the CSV mapping file, that contains details about the propery and method
# to be invoked for a given resource type
# a wildcard (*) for the type means if applies to any resource type that is supported
class CSVReader
include Singleton
MAPPINGS_FILE = File.join(File.dirname(__FILE__), 'bioschema_mappings.csv').freeze
# An iterator that yields each valid row, as a CSVMappingInfo instance
def each_row
mappings_csv.each do |row|
info = CSVMappingInfo.new(row)
yield(info) if info.valid?
end
end
private
def mappings_csv
@csv ||= CSV.read(MAPPINGS_FILE)
end
end
end
end
| true |
a3e9f81db26442c3ca386ce0688bfd215e886bec | Ruby | bmael/Raspbuddies | /ForRasp/broadcast/HashModule.rb | UTF-8 | 661 | 3 | 3 | [] | no_license | require 'digest/md5'
module HashFunctions
@@a1 = [18, 39, 3, 37, 12, 29, 7, 30, 23, 2, 5, 39, 24, 12, 26, 12, 27, 0, 25, 24, 9, 12, 9, 18, 32, 27, 38, 30, 18, 27, 12, 25]
@@a2 = [6, 9, 38, 16, 21, 26, 3, 7, 13, 5, 30, 22, 15, 19, 31, 30, 32, 9, 9, 0, 18, 10, 7, 1, 16, 6, 12, 6, 22, 3, 5, 29]
def h1(k)
result = 0
n = 0
k.each_byte do |b|
result = result + @@a1[n] * b
n = n + 1
end
return result.modulo(41)
end
def h2(k)
result = 0
n = 0
k.each_byte do |b|
result = result + @@a2[n] * b
n = n + 1
end
return result.modulo(41)
end
def hashKey(k)
md5 = Digest::MD5.hexdigest(k)
return [h1(md5), h2(md5)]
end
end
| true |
e783bfe507276084c93bdfb9eb1981dc36eba10b | Ruby | cmupakile/coursework | /w01d03/aiportLab/main.rb | UTF-8 | 621 | 2.734375 | 3 | [] | no_license | # require_relative "./airport.rb"
response = menu
while response != 'E'
case response
when 'F'
flight_info
when 'P'
passenger_info
when 'T'
terminal_info
end
response = menu
end
def menu
puts `clear`
puts "*****************************************************"
puts "*****************************************************"
puts ""
puts ""
print "(F)lights ** (P)assengers ** (T)erminal ** (E)xit: "
puts ""
puts ""
puts ""
puts "*****************************************************"
puts "*****************************************************"
gets.chomp.downcase
end
| true |
c3416aeb0dadcc686deaa73c06ad45369ebd95c7 | Ruby | puppycodes/huboard-on-heroku | /test/lib/classy_assumptions_test.rb | UTF-8 | 919 | 2.875 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class ClassyAssumptionsTest < ActiveSupport::TestCase
class BobBase
def self.bob
@bob ||= "bob"
end
def self.set_bob(bob)
@bob = bob
end
def perform
payload
end
end
class Frank < BobBase
def get_bob_class
self.class.bob
end
end
class Bill < BobBase
def initialize
@bob = "bill"
end
def payload
"payload"
end
def get_bob
@bob
end
def get_bob_class
self.class.bob
end
end
test 'base class has access to inheritors methods' do
assert Bill.new.perform == "payload"
end
test 'class variables arent altered' do
bill = Bill.new
assert bill.get_bob_class == "bob"
assert bill.get_bob == 'bill'
frank = Frank.new
assert frank.get_bob_class == "bob"
bill.class.set_bob "bill"
assert frank.get_bob_class != bill.get_bob_class
end
end
| true |
03cc747401140c04fc6115bf9f5b07c69d0b9536 | Ruby | Rob-rls/learn_to_program | /ch10-nothing-new/english_number.rb | UTF-8 | 5,885 | 3.375 | 3 | [] | no_license | def english_number number
=begin
if number < 0
return 'Please enter a number that isn\'t negative.'
end
=end
if number == 0
return 'zero'
end
numString = ''
onesPlace = ['one', 'two','three', 'four','five','six','seven','eight','nine']
tensPlace = ['ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
teenagers = ['eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
left = number
write = left/1000000000000000000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' quindecillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' quattuordecillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' tredecillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' duodecillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' undecillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000000
left = left - write*1000000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' decillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000000
left = left - write*1000000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' nonillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000000
left = left - write*1000000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' octillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000000
left = left - write*1000000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' septillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000000
left = left - write*1000000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' sextillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000000
left = left - write*1000000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' quintillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000000
left = left - write*1000000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' quadrillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000000
left = left - write*1000000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' trillion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000000
left = left - write*1000000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' billion'
if left > 0
numString = numString + ' '
end
end
write = left/1000000
left = left - write*1000000
if write > 0
thousands = english_number write
numString = numString + thousands + ' million'
if left > 0
numString = numString + ' '
end
end
write = left/1000
left = left - write*1000
if write > 0
thousands = english_number write
numString = numString + thousands + ' thousand'
if left > 0
numString = numString + ' '
end
end
write = left/100
left = left - write*100
if write > 0
hundreds = english_number write
numString = numString + hundreds + ' hundred'
if left > 0
numString = numString + ' '
end
end
write = left/10
left = left - write*10
if write > 0
if ((write == 1) and (left > 0))
numString = numString + teenagers[left-1]
left = 0
else
numString = numString + tensPlace[write-1]
end
if left > 0
numString = numString + '-'
end
end
write = left
left = 0
if write > 0
numString = numString + onesPlace[write-1]
end
numString
end
=begin
puts english_number( 0)
puts english_number( 9)
puts english_number( 10)
puts english_number( 88)
puts english_number(100)
puts english_number(101)
puts english_number(234)
puts english_number(3211)
puts english_number(9999)
puts english_number(8134)
puts english_number(999999)
puts english_number(1000000000000)
puts english_number(1000000000000000)
puts english_number(109238745102938560129834709285360238475982374561034)
=end
| true |
1433354356edb91efb94f297596539282a764d57 | Ruby | bmangelsen/employee-reviews-102016 | /department.rb | UTF-8 | 877 | 3.453125 | 3 | [] | no_license | require_relative './employee'
class Department
attr_accessor :department_name
attr_reader :department_employees
def initialize(department_name)
@department_name = department_name
@department_employees = []
CSV.open("departments.csv", "a") do |csv|
csv << [department_name]
end
end
def add_employee(employee)
department_employees << employee
end
def sum_all_salaries
total = 0
department_employees.each do |employee|
total = yield(total, employee.salary)
end
total
end
def give_department_raises(department_wide_raise)
deserve_raises = []
department_employees.each do |employee|
if employee.good_response == true
deserve_raises << employee
end
end
deserve_raises.each do |employee|
employee.salary += (department_wide_raise / deserve_raises.count)
end
end
end
| true |
d90d8592e6d668f8f397c2d30be9d81258212182 | Ruby | department-of-veterans-affairs/vets-api | /app/models/emis_redis/veteran_status.rb | UTF-8 | 2,723 | 2.65625 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | # frozen_string_literal: true
require 'emis/veteran_status_service'
module EMISRedis
# EMIS veteran status service redis cached model.
# Much of this class depends on the Title 38 Status codes, which are:
#
# V1 = Title 38 Veteran
# V2 = VA Beneficiary
# V3 = Military Person, not Title 38 Veteran, NOT DoD-Affiliated
# V4 = Non-military person
# V5 = EDI PI Not Found in VADIR (service response only not stored in table)
# V6 = Military Person, not Title 38 Veteran, DoD-Affiliated
#
# @see https://github.com/department-of-veterans-affairs/vets.gov-team/blob/master/Products/SiP-Prefill/Prefill/eMIS_Integration/eMIS_Documents/MIS%20Service%20Description%20Document.docx
#
class VeteranStatus < Model
# Class name of the EMIS service used to fetch data
CLASS_NAME = 'VeteranStatusService'
# @return [Boolean] true if user is a title 38 veteran
def veteran?
title38_status == 'V1'
end
# @return [String] Title 38 status code
def title38_status
validated_response&.title38_status_code
end
# Returns boolean for user being/not being considered a military person, by eMIS,
# based on their Title 38 Status Code.
#
# @return [Boolean]
#
def military_person?
title38_status == 'V3' || title38_status == 'V6'
end
# Not authorized error raised if user
# doesn't have permission to access EMIS API
class NotAuthorized < StandardError
attr_reader :status
# @param status [Integer] An HTTP status code
#
def initialize(status: nil)
@status = status
end
end
# Record not found error raised if user is not found in EMIS
class RecordNotFound < StandardError
attr_reader :status
# @param status [Integer] An HTTP status code
#
def initialize(status: nil)
@status = status
end
end
private
# The emis_response call in this method returns an instance of the
# EMIS::Responses::GetVeteranStatusResponse class. This response's `items`
# is an array of one hash. For example:
# [
# {
# :title38_status_code => "V1",
# :post911_deployment_indicator => "Y",
# :post911_combat_indicator => "N",
# :pre911_deployment_indicator => "N"
# }
# ]
#
# @return [Hash] A hash of veteran status properties
#
def validated_response
raise VeteranStatus::NotAuthorized.new(status: 401) if !@user.loa3? || !@user.authorize(:emis, :access?)
response = emis_response('get_veteran_status')
raise VeteranStatus::RecordNotFound.new(status: 404) if response.empty?
response.items.first
end
end
end
| true |
f99d968d356eb063ea56fbeee94dbc2f2e15acbb | Ruby | Natirx/LV-277.TAQC | /OpenCart tests/Cart(Andrii)/pages/page.rb | UTF-8 | 721 | 2.65625 | 3 | [] | no_license | require_relative 'main'
class Page < Main
ADDTOCART_BUTTON = {css: ".product-layout:first-child button:first-child"}
CART_ONE_ITEM = {:css => "#cart-total"}
CART_BUTTON = {:xpath =>"//a[@title='Shopping Cart']"}
ITEM_FIELD ={:xpath => "//*[@id='content']//a[text()='MacBook']"}
SIME = {css: ".product-layout:first-child .price"}
def add_item_to_cart
load
click ADDTOCART_BUTTON if is_displayed?(ADDTOCART_BUTTON)
add_to_quantity
sleep 1
end
def add_item_and_press
add_item_to_cart
click CART_BUTTON
end
def get_text_from_cart
get_text CART_ONE_ITEM if is_displayed?(CART_ONE_ITEM)
end
def get_1_first_chars_from_span
get_text_from_cart[0,1].to_i
end
end
| true |
300d3373c0ff9431b92c0b86918733ccdcc6d611 | Ruby | nigelr/guesser | /guesser.rb | UTF-8 | 611 | 2.734375 | 3 | [] | no_license | require 'sinatra'
get '/' do
erb :homepage
end
get '/start' do
secret_number = rand(100)
redirect "/play/#{secret_number}/Start"
end
get '/play/:secret_number/:message' do
erb :play, locals: { secret_number: params[:secret_number], message: params[:message] }
end
post '/check/:secret_number' do
secret_number = params[:secret_number].to_i
guess = params[:guess].to_i
case
when secret_number == guess
erb :you_won
when guess > secret_number
redirect "/play/#{secret_number}/Too high"
when guess < secret_number
redirect "/play/#{secret_number}/Too low"
end
end | true |
78c6b7af77423f5af8546e60ee7246aad667e2ce | Ruby | ErickGushiken/si_project | /siproject/app/models/user.rb | UTF-8 | 3,476 | 2.765625 | 3 | [] | no_license | class User < ApplicationRecord
has_secure_password
has_many :produtos
HUMANIZED_ATTRIBUTES = {
:email => "Email",
:password => "senha",
:password_confirmation => "Confirmação de senha",
:data_nasc => "Data de nascimento",
}
# Essa função altera o nome do atributo para mostrar as mensagens de erro
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
# validates :email, presence: true, uniqueness: true
validates :nome, presence: {message: 'O campo nome é obrigatório'}
validates :data_nasc, presence: {message:'A data de nascimento é obrigatória'}
# validates :documento, presence: {message: 'não pode ser deixado em branco'}
validates :email,
presence: {message: 'O campo email é obrigatório'},
uniqueness: {message: 'Esse email já está cadastrado'},
format: {with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/, message:"Email inserido possui formato inválido"}
validate :validate_documento
validate :validate_idade
def validate_idade
if data_nasc.present? && data_nasc.to_i > 18.years.ago.to_i
errors.add(:data_nasc, 'Data de nascimento inválida, Você precisa ter mais de 18 anos.')
end
end
def validate_documento
if tipo==1 && !check_cpf(documento)
errors.add(:documento, 'CPF inválido.')
end
if tipo==0 && !check_cnpj(documento)
errors.add(:documento, 'CNPJ inválido.')
end
end
def check_cpf(cpf=nil)
return false if cpf.nil?
nulos = %w{12345678909 11111111111 22222222222 33333333333 44444444444 55555555555 66666666666 77777777777 88888888888 99999999999 00000000000 12345678909}
valor = cpf.scan /[0-9]/
if valor.length == 11
unless nulos.member?(valor.join)
valor = valor.collect{|x| x.to_i}
soma = 10*valor[0]+9*valor[1]+8*valor[2]+7*valor[3]+6*valor[4]+5*valor[5]+4*valor[6]+3*valor[7]+2*valor[8]
soma = soma - (11 * (soma/11))
resultado1 = (soma == 0 or soma == 1) ? 0 : 11 - soma
if resultado1 == valor[9]
soma = valor[0]*11+valor[1]*10+valor[2]*9+valor[3]*8+valor[4]*7+valor[5]*6+valor[6]*5+valor[7]*4+valor[8]*3+valor[9]*2
soma = soma - (11 * (soma/11))
resultado2 = (soma == 0 or soma == 1) ? 0 : 11 - soma
return true if resultado2 == valor[10] # CPF válido
end
end
end
return false # CPF inválido
end
def check_cnpj(cnpj=nil)
return false if cnpj.nil?
nulos = %w{11111111111111 22222222222222 33333333333333 44444444444444 55555555555555 66666666666666 77777777777777 88888888888888 99999999999999 00000000000000}
valor = cnpj.scan /[0-9]/
if valor.length == 14
unless nulos.member?(valor.join)
valor = valor.collect{|x| x.to_i}
soma = valor[0]*5+valor[1]*4+valor[2]*3+valor[3]*2+valor[4]*9+valor[5]*8+valor[6]*7+valor[7]*6+valor[8]*5+valor[9]*4+valor[10]*3+valor[11]*2
soma = soma - (11*(soma/11))
resultado1 = (soma==0 || soma==1) ? 0 : 11 - soma
if resultado1 == valor[12]
soma = valor[0]*6+valor[1]*5+valor[2]*4+valor[3]*3+valor[4]*2+valor[5]*9+valor[6]*8+valor[7]*7+valor[8]*6+valor[9]*5+valor[10]*4+valor[11]*3+valor[12]*2
soma = soma - (11*(soma/11))
resultado2 = (soma == 0 || soma == 1) ? 0 : 11 - soma
return true if resultado2 == valor[13] # CNPJ válido
end
end
end
return false # CNPJ inválido
end
end
| true |
c0f78ad534678f3523afe2f744f0d6f11911e80a | Ruby | demileee/ruby_fundamentals4 | /fizzbuzz.rb | UTF-8 | 270 | 3.34375 | 3 | [] | no_license | hundred = []
counter = 0
until counter == 100
counter += 1
z = counter
hundred << z
end
hundred.each do |num|
if (num % 3) == 0 && (num % 5) == 0
puts "BitMaker"
elsif (num % 3) == 0
puts "Bit"
elsif (num % 5) == 0
puts "Maker"
else
end
end
| true |
ae7fffb8f589f4cda155249e9445f0d10b6b3750 | Ruby | cul/json_csv | /lib/json_csv/utils.rb | UTF-8 | 2,197 | 3.5 | 4 | [] | no_license | module JsonCsv
module Utils
# Returns true for empty strings, empty arrays, or empty hashes.
# Also returns true for strings that only contain whitespace.
# Returns false for all other values, including booleans and numbers.
def self.removable_value?(value)
return true if value.respond_to?(:empty?) && value.empty? # empty string, empty array, or empty hash
return true if value.is_a?(String) && value.strip.empty? # string that only contains whitespace
return true if value.nil?
false
end
def self.recursively_remove_blank_fields!(hash_or_array)
return if hash_or_array.frozen? # We can't modify a frozen value, so we won't.
if hash_or_array.is_a?(Array)
# Recurse through non-empty elements
hash_or_array.each do |element|
recursively_remove_blank_fields!(element) if element.is_a?(Hash) || element.is_a?(Array)
end
# Delete blank array element values on this array level (including empty object ({}) values)
hash_or_array.delete_if do |element|
removable_value?(element)
end
elsif hash_or_array.is_a?(Hash)
hash_or_array.each_value do |value|
recursively_remove_blank_fields!(value) if value.is_a?(Hash) || value.is_a?(Array)
end
# Delete blank hash values on this hash level (including empty object ({}) values)
hash_or_array.delete_if do |_key, value|
removable_value?(value)
end
else
raise ArgumentError, 'Must supply a hash or array.'
end
hash_or_array
end
# Recursively goes through an object and strips whitespace,
# modifying the object's nested child hashes or array.
# Note: This method modifies hash values, but does not
# modify hash keys.
def self.recursively_strip_value_whitespace!(obj)
if obj.is_a?(Array)
obj.each do |element|
recursively_strip_value_whitespace!(element)
end
elsif obj.is_a?(Hash)
obj.each_value do |value|
recursively_strip_value_whitespace!(value)
end
elsif obj.is_a?(String)
obj.strip!
end
obj
end
end
end
| true |
bb03a7414910af770605c9c962e261eb092cc500 | Ruby | josevictorferreira/store_api | /app/models/stock_item.rb | UTF-8 | 1,200 | 2.859375 | 3 | [] | no_license | class StockItem < ApplicationRecord
belongs_to :product
belongs_to :store
validates_presence_of :product, :store
validates :items, numericality: { greater_than_or_equal_to: 0 }
validates :product, uniqueness: { scope: :store }
def add_stock_item(number)
StockItem.add_items(self.id, number)
self.reload
end
def remove_stock_item(number)
StockItem.remove_items(self.id, number)
self.reload
end
def self.add_items(item_id, num_items)
if num_items.positive?
StockItem.transaction do
item = StockItem.find_by_id(item_id)
item.with_lock do
item.items += num_items
item.save!
end
end
else
raise ArgumentError.new(
'Invalid amount to add to stock. It must be a positive number.'
)
end
end
def self.remove_items(item_id, num_items)
if num_items.positive?
StockItem.transaction do
item = StockItem.find_by_id(item_id)
item.with_lock do
item.items -= num_items
item.save!
end
end
else
raise ArgumentError.new(
'Invalid amount to add to stock. It must be a positive number.'
)
end
end
end
| true |
5319c012e414cc045bd74f5f75afc96300a7800e | Ruby | jpserra/shorty | /lib/shorty/config.rb | UTF-8 | 507 | 2.71875 | 3 | [] | no_license | module Shorty
class Config
def initialize(config_file = nil)
@config_file =
config_file || File.dirname(__FILE__) + '/../../config/shorty_config.rb'
end
def fetch(key)
config.fetch(key)
end
def [](key)
config[key]
end
private
def config
return @config if @config
raise "#{@config_file} doesn't exist" unless File.exist?(@config_file)
config = {}
eval(File.read(@config_file))
@config = config
end
end
end
| true |
3980cd30af65870885fc75e7c624a48cb5c6f02b | Ruby | Hibasan/Ruby-01 | /janken.rb | UTF-8 | 4,653 | 4.40625 | 4 | [] | no_license | # プレイヤー(自分)に「0~2」を入力させるロジックを書きます。
class Player
def hand
# プレイヤーにじゃんけんの手を選択させる文章を表示させます。
puts "数字を入力してください。"
puts "0:グー, 1:チョキ, 2:パー"
# 変数「input_hand」にプレイヤーの入力値を代入します。
# ヒント:getsメソッドについて調べてみましょう。
input_hand =gets.to_i
# 「input_hand」が「0, 1, 2」のいずれかだと繰り返し処理を終了し、それ以外(アルファベットも含む)だと繰り返し処理を継続します。
while true
if input_hand == 0 || input_hand == 1 || input_hand == 2
# if 「input_hand」が「0, 1, 2」のいずれかの場合だった場合
# ヒント:include?メソッドについて調べてみましょう。
return input_hand
# 「input_hand」をそのまま返す。
# ヒント:戻り値を返して繰り返し処理を終了させたい場合、「return」を使用します。
else
# else それ以外の場合
puts "0〜2の数字を入力してください。"
puts "0:グー, 1:チョキ, 2:パー"
input_hand = gets.to_i
# プレイヤーに「0〜2」を入力させる文章を表示させる。
# puts "0〜2の数字を入力してください。"
# puts "0:グー, 1:チョキ, 2:パー"
# 変数「input_hand」にプレイヤーの入力値を代入します。
end
# end if文のend
end
end
end
# 相手が「0~2」の値をランダムに生成するロジックを書きます。
class Enemy
def hand
# グー、チョキ、パーの値をランダムに取得する。
input_hand = rand(0..2)
return input_hand
end
end
# プレイヤー(自分)が入力した「0~2」と、敵がランダムで生成した「0~2」をじゃんけんをさせて、その結果をコンソール上に出力するロジックを書きます。
class Janken
def pon(player_hand, enemy_hand)
# 変数「janken」に["グー", "チョキ", "パー"]を代入します。
janken = ["グー", "チョキ", "パー"]
#「相手の手は#{相手の手}です。」と出力させます。
puts "あなたの手は#{janken[player_hand]}です。"
puts "相手の手は#{janken[enemy_hand]}です。"
# Playerクラスの戻り値とEnemyクラスの戻り値からじゃんけんするロジックを作成します。
# Playerクラスの戻り値(player_hand)とEnemyクラスの戻り値(enemy_hand)の値が同じだった場合
# 「あいこ」を出力します。
if
player_hand == enemy_hand
puts "EVEN...NEXT"
return true
#「true」を返してじゃんけんを繰り返し実行させます。
# ヒント:「return」を使って戻り値を返すことができます。しかし、Rubyでは戻り値を返す場合、「return」を省略するのが一般的です。
elsif # もしも下記の組み合わせだった場合
(player_hand - enemy_hand + 3) % 3 == 2
puts "YOU WIN"
return false
# (player_hand == 0 && enemy_hand == 1) || (player_hand == 1 && enemy_hand == 2) || (player_hand == 2 && enemy_hand == 0)
#「あなたの勝ちです」を出力します。
#「false」を返してじゃんけんを終了させます。
else
(player_hand - enemy_hand + 3) % 3 == 1
puts "YOU LOSE"
return false
#「あなたの負けです」を出力します。
#「false」を返してじゃんけんを終了させます。
end
end
end
# じゃんけんゲームを実行するロジックを書きます。
class GameStart
# selfを使用することで、GameStartをインスタンス化することなく、クラス名を使ってjankenponメソッドを呼び出せます。
def self.jankenpon
# 変数にインスタンス化したものを代入します。
player = Player.new
enemy = Enemy.new
janken = Janken.new
next_game = true
# 「next_game」が「false」だと繰り返し処理を終了し、「true」だと繰り返し処理を継続します。
while next_game == true
# 変数「next_game」にじゃんけんを実行して返ってきた値(戻り値)を代入します。
#「janken.pon(player.hand, enemy.hand)」でじゃんけんを実行しています。
next_game = janken.pon(player.hand, enemy.hand)
end
end
end
# クラス名を使ってjankenponメソッドを呼び出します。
GameStart.jankenpon
| true |
3342b9acf7725d1d3a0e7c64864732cc9fa3e0c0 | Ruby | MrDevo/SimpleRubyProjects | /Iterators.rb | UTF-8 | 448 | 3.75 | 4 | [] | no_license | i = 5
i.times do
puts "Countdown #{i}"
i-=1
end
puts "Blast off!!"
puts "\n"
#=========================================
5.times do |i|
puts "Countdown #{5-i}"
end
puts "Blast off!!!"
puts "\n"
#=========================================
5.downto(1) {|i| puts "Countdown #{i}"}
puts "Blast off!!!"
puts "\n"
#=========================================
fruits = ["banana", "apple", "pear"]
fruits.each do |fruit|
puts fruit.capitalize
end | true |
628b39c3201ffe916ac5b8c8b6c1e08667087e57 | Ruby | anthonyneedles/WISE-HEADACHE-JASH | /cosmos/procedures/plot_test.rb | UTF-8 | 186 | 2.65625 | 3 | [] | permissive | load 'cosmos/gui/line_graph/line_graph_script.rb'
x = [0.0, 1.0, 2.0, 3.0, 4.0]
y1 = [10.5, 9.6, 7.7, 6.8, 7.4]
y2 = [10.2, 9.1, 7.3, 6.5, 7.8]
plot(x, y1)
plot(x, y1, 'y1', y2, 'y2')
| true |
41043bfd27f5225bd689fd7e510213848f4da0d0 | Ruby | Linus-Cson-Ferdinand-Bostrom/Uppgifter | /30_concatenate/lib/concatenate.rb | UTF-8 | 99 | 3.015625 | 3 | [] | no_license | def concatenate (num1, num2)
blah1 = num1.to_s
blah2 = num2.to_s
return blah1 + blah2
end
| true |
dd11517abc8d6cd32a34b4d4e923a75789a593f7 | Ruby | ltg7vp/Ruby-stuff | /weatherApp.rb | UTF-8 | 1,901 | 3.84375 | 4 | [] | no_license | require 'open-uri'
require 'json'
#Weather API returns Kelvins so we'll have to use these conversion functions later on
def KelvinToCelcius(kelvin)
return (kelvin - 273.15).round(2)
end
def KelvinToFahrenheit(kelvin)
return (kelvin * 9/5 - 459.67).round(2)
end
params = Array.new
puts "Pass location parameters in the following format: '[City], [State]'"
print "> "
params << gets.chomp
if params.length != 1
puts "Error: Parameters not formatted correctly.
Please pass location parameters in the following format: '[City], [State]'"
else
#Stringing together the arguments to fit into a URL
search = Array.new
params.each do |argv|
search << argv
end
search = search.join
#Putting together the URL
baseurl = "http://api.openweathermap.org/data/2.5/weather?q="
appid = "&APPID=aade92db2619aca3f567b1ac542128b5"
fullurl = "#{baseurl}#{search}#{appid}"
#Read the data at the URL
data = open(fullurl).read
json = JSON.parse(data)
#If the city isn't found, lets get out of here!
if json['cod'] == 400
abort("City not found. Please try again.")
end
#Assigning variables using conversion functions
tempc = KelvinToCelcius(json["main"]["temp"])
lowc = KelvinToCelcius(json["main"]["temp_min"])
highc = KelvinToCelcius(json["main"]["temp_max"])
tempf = KelvinToFahrenheit(json["main"]["temp"])
lowf = KelvinToFahrenheit(json["main"]["temp_min"])
highf = KelvinToFahrenheit(json["main"]["temp_max"])
#Output to console
puts ""
puts " " * 8 + "Forecast for #{search}"
puts " " * 10 + "Temperature (F°) #{tempf}° (hi: #{highf}/lo: #{lowf})"
puts " " * 10 + "Temperature (C°) #{tempc}° (hi: #{highc}/lo: #{lowc})"
puts ""
puts " " * 10 + "Description: #{json['weather'].first['description']}"
puts " " * 10 + "Wind: #{json['wind']['speed']} mph"
puts " " * 10 + "Cloudiness: #{json['clouds']['all']}%"
puts ""
end
| true |
8ca062405d1ae6b7307b88898d86c89fd3c4a93b | Ruby | rodenr/ruby_assignment | /9.rb | UTF-8 | 602 | 3.53125 | 4 | [] | no_license | class Numeric
@@currencies={'yen'=>0.013, 'euro'=>1.292, 'rupee'=>0.019, 'dollar'=>1}
def method_missing(method_id)
singular_currency = method_id.to_s.gsub(/s$/,'')
if @@currencies.has_key?(singular_currency)
self * @@currencies[singular_currency]
else
super
end
end
def in(currency)
# raise 'Param needs to be symbol' unless currency.kind_of? Symbol
singular_currency = currency.to_s.gsub(/s$/, '')
self / @@currencies[singular_currency]
end
end
p 5.yen.in(:dollar).in(:yen)
p 5.yen.in(:dollars)
p 0.065.dollars.in(:yen)
p 1.dollar.in(:rupees)
p 10.rupees.in(:euro)
| true |
6b8b389aa14b399483f3b0198698329f2b4c1661 | Ruby | ThiQuynhTramPHAM/Coderubycaesar | /chiffre_de_cesar.rb | UTF-8 | 454 | 3.59375 | 4 | [] | no_license | puts "Que voudriez vous coder?"
mot = gets.chomp
puts "Quel ecart souhaitez vous avoir"
facteur = gets.chomp.to_i
def cipher(mot, facteur)
nouveau_mot = ""
mot.each_char do |i|
facteur.times do
if(i == "z")
i = "a"
next
elsif(i == "Z")
i = "A"
next
end
i.next!
i == "%" ? i = " " : ""
end
nouveau_mot += i
end
puts nouveau_mot
end
cipher(mot, facteur) | true |
e5e75c77ee58312b28ee1515a6c670cb09ff42d5 | Ruby | siruguri/track_status | /app/services/text_stats/document_universe.rb | UTF-8 | 434 | 2.640625 | 3 | [] | no_license | module TextStats
class DocumentUniverse
def initialize
@_counts = {}
@_univ_size = 0
end
def add(doc_model)
@_univ_size += 1
doc_model.terms.each do |k|
@_counts[k] ||= 0
@_counts[k] += 1
end
self
end
def universe_count(term)
if @_counts[term]
@_counts[term]
else
1.042
end
end
alias :df :universe_count
end
end
| true |
e35155785d95a0965a2282277112f4a0ec133e1a | Ruby | sho12chk/ruby_lesson | /original/sample.rb | UTF-8 | 2,734 | 3.515625 | 4 | [] | no_license | #################################
##### 昼ドラ風プログラム #######
#################################
#共通クラス
class User
attr_accessor :name,:age,:love_word,:hate_word
def initialize(name:,age:,love_word:,hate_word:)
self.name = name
self.age = age
self.love_word = love_word
self.hate_word = hate_word
end
end
=begin
<男側クラス>
今回の目的は継承の値の受け渡しの確認=>
他子クラスのインスタンス変数は持ってこれなかった。
配列や、変数に代入するといける。
=end
class Man < User
attr_accessor :money
def initialize(name:,age:,love_word:,hate_word:,money:)
super(name: name,age: age,love_word: love_word,hate_word: hate_word)
self.money = money
end
#TOKIOのメンバーが登場する分岐がある
def tokio_members_hi(cool_members,woman_serif,word_h,word_l)
text1 = "=>(心の声をいち早く察知)僕の年収は#{self.money}万円だよ。\n=>"
text2 = <<~EOS
=>やぁ、僕の友達を紹介するよ。
#{cool_members[0]}、#{cool_members[1]}、#{cool_members[2]}だよ。
みんなで一緒に飲もうよ\n=>#{word_l}
EOS
if /年収/ =~ woman_serif
self.money >= 500 ? text1 += word_l : text1 += word_h
else
text1 = text2
end
text1
end
def like(arry_w,decide_words)
text = ""
if arry_w[2] <= 30 && decide_words.include?("深田恭子にそっくりな")
puts "";sleep(4)
text += "#{self.name}は、#{arry_w[0]}の#{arry_w[1]}なところが#{self.love_word}"
else
text += "#{self.hate_word}"
end
text
end
def info
<<~text
都会の真ん中で繰り広げられる諸行無常。
愛と現実の間で揺れ動きながら、さまよう東京砂漠。
#{self.name}#{self.age}歳...
text
end
end
#<女性側クラス>
class Woman < User
attr_accessor :spec
def initialize(name:,age:,love_word:,hate_word:,spec:)
super(name: name,age: age,love_word: love_word,hate_word: hate_word)
self.spec = spec
end
def question(serifs)
text =<<~EOS
\n
------------------------------------
相席屋に初めてやってきた#{self.name}
EOS
serifs.each.with_index(1) do|item,i|
text += "\n心の声#{i}:#{item}\n"
end#textに代入しないとiが出力されない
text
end
def self.select(serifs,answer)
serifs[answer-1] ||= "1か2の数字を入力してください"
"\n選んだセリフ「#{serifs[answer-1]}」"
end
end
| true |
ea8869bcb6069344588aaa07949e91c32788b5ee | Ruby | nounch/bat-game | /entities/npc.rb | UTF-8 | 896 | 3.15625 | 3 | [] | no_license | class NPC
attr_accessor :x, :y, :is_dead
def initialize(**options)
@x = options[:x] || 0
@y = options[:y] || 0
@screen = options[:screen] || nil
@game = options[:game] || nil
@tile = options[:tile] || 'w'
@killable = options[:killable] || true
@last_tick = 0
@do_tick = true
@is_dead = false
end
def wander()
x1 = @x + [0, 1, -1].sample()
y1 = @y + [0, 1, -1].sample()
if x1 >= 0 && x1 < @screen.width
@x = x1
end
if y1 >= 0 && y1 < @screen.height
@y = y1
end
end
def kill()
@is_dead = true
end
def tick()
if @do_tick
@last_tick += 1
if @last_tick > 10
@last_tick = 0
if !@is_dead
wander()
else
@tile = @game.tile_types[:dead_body]
end
end
render()
end
end
def render()
@screen.put(@x, @y, @tile)
end
end
| true |
bc88ca7f2454698194fbd1e9b7b3b62273d208e6 | Ruby | jokercsi/RubyPractice | /04.Query Parts and Web Forms/student_data_start.rb | UTF-8 | 1,079 | 3.25 | 3 | [] | no_license | # definition of simple Student class
Student = Struct.new(:number, :familyname, :givenname, :english, :math, :average)
# initialization of array students
students = [
Student.new("12345678", "Reigai", "Taro", 80, 62), # 例外 太郎
Student.new("12349875", "Reidai", "Hanako", 76, 65), # 例題 花子
Student.new("12349458", "Gambare", "Manabu", 56, 66), # 頑張 学
Student.new("12342584", "Sample", "Tatoe", 34, 70), # サンプル 例恵
Student.new("12348347", "Sugaku", "Tokeko", 55, 100), # 数学 解子
Student.new("12341948", "Girigiri", "Tariyasu", 60, 60), # ぎりぎり 足康
Student.new("12348463", "English", "Perfect", 100, 56), # 英語 完璧
Student.new("12347628", "Asobi", "Saboro", 20, 25), # 遊日 サボ郎
Student.new("12344924", "Kurikaeshi", "Mawaroh", 77, 30), # 繰返 回郎
Student.new("12341369", "Seiretu", "Junko", 69, 80) # 整列 順子
] | true |
e35e6071752a002213a120a1099b164e69da83e9 | Ruby | syhsyh9696/blog-notification-ruby | /lib/module.rb | UTF-8 | 1,363 | 2.515625 | 3 | [] | no_license | # encoding: utf-8
module Unicorn
version = "1.3.5"
def get_time(authentication)
updatetime = Hash.new
File.open("../resources/allblog.ini", "r") do |io|
while line = io.gets
line.chomp!
updatetime[line] = Time.parse(pushed_at(line, authentication).to_s.gsub!(/T/, " ").gsub!(/Z/, ""))
end
end
return updatetime
end
def pushed_at(user, authentication)
return authentication.repos(user, "#{user}.github.io").to_h['pushed_at']
end
def user_list
user = Array.new
File.open("../resources/chat_id.ini", "r") do |io|
while line = io.gets
line.chomp!
user << line
end
end
return user
end
def store_chatid(chat_id)
chat_id = chat_id.to_s
flagbit = true
user_list.each do |user|
next if user != chat_id
flagbit = false if user == chat_id
end
if (flagbit)
io_temp = File.open("../resources/chat_id.ini", "a")
io_temp << chat_id << "\n"
io_temp.close
end
end
module_function :get_time
module_function :pushed_at
module_function :user_list
module_function :store_chatid
end
| true |
9d606b27a77fbc466f0833df97bfaea12c80780b | Ruby | spaldingVance/RB101 | /lesson_3/sum_or_product.rb | UTF-8 | 631 | 4.5 | 4 | [] | no_license | puts ">> Please enter an integer greater than zero"
top_of_range = gets.chomp.to_i
puts ">> Enter s to compute the sum, p to compute the product"
loop do
choice = gets.chomp.downcase
if choice == 's'
sum = 0
(1..top_of_range).each {|x| sum += x}
puts "The sum of the integers between 1 and #{top_of_range} is #{sum}."
break
elsif choice == 'p'
product = 1
(1..top_of_range).each {|x| product *= x}
puts "The product of the integers between 1 and #{top_of_range} is #{product}."
break
else
puts "Please enter a valid choice: s to compute the sum or p to compute the product: "
end
end
| true |
42bc11cc757636501161da4b714f6410011b4c20 | Ruby | martin-kirilov/ProgrammingTechnology1task | /h16/subarray_count.rb | UTF-8 | 268 | 3.53125 | 4 | [] | no_license | class Array
def subarray_count subArr
arrCount = 0
if subArr.get
self.each_index do |x|
if self[x] == subArr[0] && self[x+1] == subArr[1]
arrCount += 1
end
end
arrCount
end
end | true |
ee97ca46660f7f838e325cf5087d5722a9ae510f | Ruby | allagitgub/ttt-game-status-online-web-sp-000 | /lib/game_status.rb | UTF-8 | 1,327 | 3.859375 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Helper Method
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,4,8],
[2,4,6],
[0,3,6],
[1,4,7],
[2,5,8]
]
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
def won?(board)
WIN_COMBINATIONS.detect do |win_combination|
(board[win_combination[0]] == "X" && board[win_combination[1]] == "X" && board[win_combination[2]] == "X") ||
(board[win_combination[0]] == "O" && board[win_combination[1]] == "O" && board[win_combination[2]] == "O")
end
end
def full?(board)
board.select{ |item| item != " " && !item.nil? && item != ""}.size == 9
end
def draw?(board)
!(won?(board) || !full?(board))
end
def over?(board)
won?(board) || full?(board) || draw?(board)
end
def winner(board)
if(won?(board))
if( WIN_COMBINATIONS.detect {|win_combination|
(board[win_combination[0]] == "X" && board[win_combination[1]] == "X" && board[win_combination[2]] == "X") })
return "X"
else
return "O"
end
end
nil
end
board = ["X", "O", " ", " ", "O", " ", " ", "O", "X"]
value = won?([" "," "," "," "," "," "," "," "," "])
value1 = full?([" "," "," "," "," "," "," "," "," "])
value2 = draw?(board)
value3 = winner(board)
#value1 = full?([" "," "," "," "," "," "," "," "," "])
puts "value #{value3}"
# Define your WIN_COMBINATIONS constant
| true |
650ea84d53ffccbf58e134f745117454ceb8dd7d | Ruby | harshjainmove/training | /day2/test6.rb | UTF-8 | 444 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env ruby
# hashes can use any objects as keys
class CelestialBody
attr_accessor :name, :type
end
default_body = CelestialBody.new
default_body.type = 'planet'
bodies = Hash.new(default_body)
bodies['Mars'].name = 'Mars'
p bodies['Mars']
bodies['Europa'].name = 'Europa'
bodies['Europa'].type = 'Moon'
p bodies['Europa']
bodies['Venus'].name = 'Venus'
p bodies['Mars']
p bodies['Europa']
p bodies['Venus']
puts bodies
| true |
825bc87c81ae14d21e86372153dcc96a970f3a66 | Ruby | tmurrell2020/cartoon-collections-onl01-seng-pt-090820 | /cartoon_collections.rb | UTF-8 | 450 | 3.25 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(dwarves)
dwarves.each_with_index do |names, index|
puts "#{index+1}, #{names}"
end#
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.map do |elements|
"#{elements.capitalize}!"
end
end
def long_planeteer_calls(calls)
calls.any?{|call| call.length > 4}
end
def find_the_cheese(food)
cheese_types = ["cheddar", "gouda", "camembert"]
food.detect{|cheese| cheese_types.include?(cheese)}
end
| true |
5d364b90f812810ddbc57325c194571ae23420cc | Ruby | freerange/goos-ruby | /app/auction_message_translator.rb | UTF-8 | 1,767 | 3.015625 | 3 | [] | no_license | require "price_source"
class AuctionMessageTranslator
class AuctionEvent
def initialize
@fields = Hash.new
end
def type
return get("Event")
end
def current_price
return get_int("CurrentPrice")
end
def increment
return get_int("Increment")
end
def get_int(field_name)
return Integer(get(field_name))
end
def get(field_name)
return @fields.fetch(field_name)
end
def add_field(field)
pair = field.split(":")
@fields.store(pair[0].strip, pair[1].strip)
end
def is_from(sniper_id)
return (sniper_id == bidder) ? PriceSource::FROM_SNIPER : PriceSource::FROM_OTHER_BIDDER
end
private
def bidder
return get("Bidder")
end
class << self
def from(message_body)
event = AuctionEvent.new
fields_in(message_body).each do |field|
event.add_field(field)
end
return event
end
def fields_in(message_body)
message_body.split(";")
end
end
end
def initialize(sniper_id, listener, failure_reporter)
@sniper_id, @listener, @failure_reporter = sniper_id, listener, failure_reporter
end
def processMessage(chat, message)
message_body = message.getBody
translate(message_body)
rescue => parse_exception
@failure_reporter.cannot_translate_message(@sniper_id, message_body, parse_exception)
@listener.auction_failed
end
def translate(message_body)
event = AuctionEvent.from(message_body)
event_type = event.type
if "CLOSE" == event_type
@listener.auction_closed
elsif "PRICE" == event_type
@listener.current_price(event.current_price, event.increment, event.is_from(@sniper_id))
end
end
end
| true |
1e3e07c9df56b0f47bf3619a40068fc3e4e1414b | Ruby | mauriciordz/MetodosDestructivos | /MetodosDestructivos.rb | UTF-8 | 1,767 | 4.3125 | 4 | [] | no_license | # Ivan y Mauricio
# Métodos Destructivos
# Martes 7 de Junio 2016
# name = "Fernando"
# puts "Valor de name: #{name}"
# puts "Llamando al método reverse en name : #{name.reverse}"
# puts "Valor de name despues de pasarlo por reverse: #{name}"
# puts "Llamando al método reverse! en name : #{name.reverse!}"
# puts "Valor de name después de pasarlo por reverse!: #{name}"
# ##Con SIN Destructible
# def reverse(string)
# array = []
# cadena = ""
# array = string.split('')
# my_hash={ }
# array.each_with_index do |valor,index|
# my_hash[valor] = index
# end
# my_hash = my_hash.sort_by { |valor, index| -index }
# my_hash.each{ |valor, index| cadena << valor }
# cadena
# end
# p str = "hola"
# p str = reverse(str)
# p str
# p var = "hola"
# p var.
# p var
# p reverse("Hola") == "aloH"
# class String
# def mtest
# self.upcase
# end
# def mtest!
# string = self
# string = string.upcase
# end
# end
# p var = "mau"
# p var.mtest!
# p var
#Con con Destructible
# def reverse_des(string)
#
# array = []
# cadena = ""
# array = string.split('')
#
# my_hash={ }
# array.each_with_index do |valor,index|
# my_hash[valor] = index
# end
#
# my_hash.sort { |valor, index| valor[1] <=> index[1] }
#
# my_hash.each { |valor, index| cadena << valor }
#
# cadena
#
# end
#
# p reverse_des("Hola") #== "aloH"
array = [2,5,14,6,3,9,4]
puts "Valor de mi arreglo array es: #{array}"
puts "Llamando al método sort en array : #{array.sort}"
puts "Valor de array despues de pasarlo por sort: #{array}"
puts "Llamando al método sort! en array : #{array.sort!}"
puts "Valor de array después de pasarlo por sort!: #{array}"
| true |
97bebf101ae663ff5f98d67c05ea648c2f01887f | Ruby | eiji03aero/dprb | /lib/dprb/decorator.rb | UTF-8 | 1,476 | 3.265625 | 3 | [] | no_license | module DPRB
module Decorator
# Problem
# We need to vary the responsibilities of an object, adding some features.
#
# Solution
# In the Decorator pattern we create an object that wraps the real one, and implements the same interface and forwarding method calls. However, before delegating to the real object, it performs the additional feature. Since all decorators implement the same core interface, we can build chains of decorators and assemble a combination of features at runtime.
class SimpleWriter
def initialize(path)
@file = File.open(path, 'w')
end
def write_line(line)
@file.print(line)
@file.print("\n")
end
def pos
@file.pos
end
def rewind
@file.rewind
end
def close
@file.close
end
end
class WriterDecorator
def initialize(real_writer)
@real_writer = real_writer
end
def write_line(line)
@real_writer.write_line(line)
end
def pos
@real_writer.pos
end
def rewind
@real_writer.rewind
end
def close
@real_writer.close
end
end
class NumberingWriter < WriterDecorator
def initialize(real_writer)
super(real_writer)
@line_number = 1
end
def write_line(line)
@real_writer.write_line("#{@line_number}: #{line}")
@line_number += 1
end
end
end
end
| true |
16a64dd517cca3013bb593ed6fc5632c038b3caa | Ruby | tianshuai/xiaomajj | /app/models/captcha.rb | UTF-8 | 593 | 2.65625 | 3 | [] | no_license | class Captcha < ActiveRecord::Base
#常量
KIND = {
#邮箱验证
email: 1,
#手机验证
phone: 2
}
#限制发送短信/email间隔
def is_expire_message?
return true if (self.expires_at + 60) < Time.now.to_i
return false
end
#是否过期
def is_expire?
if self.kind==1
n = 3600
elsif self.kind==2
n = 600
else
n = 600
end
return true if (self.expires_at + n) < Time.now.to_i
return false
end
#生成手机验证码(6位随机数字)
def self.generate_phone_code
rand(100000..999999)
end
end
| true |
882c6cbc85cb19d07712969d26ecdbc2d5fab7b6 | Ruby | joshisaurabh/learn_ruby | /01_temperature/temperature.rb | UTF-8 | 90 | 2.78125 | 3 | [] | no_license | def ftoc(faren)
(faren-32.0)*(5.0/9.0)
end
def ctof(celcius)
(celcius*9.0/5.0)+32
end
| true |
19a971a78f9bea7eb645dc85ce51b9bda7ac5d9a | Ruby | pamnunez/learn_ruby | /03_simon_says/simon_says.rb | UTF-8 | 521 | 3.625 | 4 | [] | no_license | def echo(text)
text
end
def shout(text)
text.upcase
end
def repeat(*input)
if input[1] == nil
input[0] + " " + input[0]
else
((input[0]+" ")*(input[1]-1)) + input[0]
end
end
def start_of_word(word, num)
word[0, num]
end
def first_word(text)
text[/\w+/]
end
def titleize(text)
shorts = ["and", "over", "the"]
text_arr = text.split(" ").each do |w|
w.capitalize! unless shorts.include?(w)
end
text_arr[0].capitalize!
text_arr.join(" ")
end
| true |
a4a8e7b0ebf816d387a9b7a159733374ddeb0a33 | Ruby | charliejp0311/programming-univbasics-4-intro-to-hashes-lab-online-web-prework | /intro_to_ruby_hashes_lab.rb | UTF-8 | 1,182 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def new_hash
# return an empty hash
new_h = Hash.new
end
def my_hash
# return a valid hash with any key/value pair of your choice
person = {
:first_name => "Charlie",
:last_name => "Pelton",
:house_number => 2 ,
:house_street => "Lee Ct.",
:house_city => "DeKalb",
:house_zip_code => 60115,
:house_state => "IL"
}
end
def pioneer
# return a hash with a key of :name and a corresponding value of 'Grace Hopper'
lewis = {:name => "Grace Hopper"}
end
def id_generator
# return a hash with a key :id assigned to positive integer
new_cust = {:id => 4}
end
def my_hash_creator(key, value)
# return a hash that includes the key and value parameters passed into this method
spec = {key => value}
end
def read_from_hash(hash, key)
# return the correct value using the hash and key parameters
p hash[key]
end
def update_counting_hash(hash, key)
# given a hash an a key as parameters, return an updated hash
# if the provided key is not present in the hash, add it and assign it to the value of 1
# if the provided key is present, increment its value by 1
if hash[key]
hash[key] += 1
else
hash[key] = 1
end
p hash
end
| true |
f33233d23087ce3481793053d7c1ba708121cd83 | Ruby | ktakenaka/trial-ruby-zip | /main.rb | UTF-8 | 1,661 | 2.59375 | 3 | [] | no_license | require 'bundler'
Bundler.require
require "tmpdir"
require 'securerandom'
require "active_support/core_ext"
puts "environment variable 'TMPDIR' is #{ENV["TMPDIR"]}"
user = "Bamboo"
file_id = SecureRandom.hex(10)
file_hash = {
theme: "home work",
section1: {
question1: 1,
question2: "hoge"
},
section2: {
question1: "fuga",
question2: [1, 3, 6]
}
}
# ref: https://docs.ruby-lang.org/ja/latest/class/Tempfile.html
# ref: https://docs.ruby-lang.org/ja/latest/method/Dir/s/mktmpdir.html
puts "--- the directory is removed after block ---"
Dir.mktmpdir([user, file_id], Bundler.root) do |dir|
@tempdir = dir
puts "#{user}'s file (#{file_id}) is at #{dir}"
File.open("#{dir}/homework.xml", "w") do |fp|
fp.puts file_hash.to_xml
end
end
puts "Tempdir after use. Does it still exists?: #{FileTest.directory?(@tempdir)}"
puts "--- zip directory including xml file ---"
dir = Dir.mktmpdir([user, file_id], Bundler.root)
puts "the dir is at #{dir}"
file_name = "homework.xml"
homework_file = "#{dir}/#{file_name}"
zip_name = "#{Bundler.root}/submit.zip"
begin
# create xml file
File.open(homework_file, "w") do |fp|
fp.puts(file_hash.to_xml)
puts "File is #{fp}"
puts file_hash.to_xml
end
# create zip
Zip::File.open(zip_name, Zip::File::CREATE) do |zip|
zip.add(file_name, homework_file)
# The way2 as below seems more simple in this case
zip.get_output_stream("another_way.xml") { |f| f.write file_hash.to_xml }
end
ensure
puts "The dir(#{dir}) is being removed"
FileUtils.remove_entry_secure dir
end
puts "Tempdir after use. Does it still exists?: #{FileTest.directory?(dir)}"
| true |
99f0e2feaf4c2184d9f2edcc5995f84d441e22cc | Ruby | J-Marriott/codewars | /6kyu/multiples_of_3_and_5_final.rb | UTF-8 | 788 | 3.765625 | 4 | [] | no_license | =begin
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once.
=end
def solution(number)
results = 0
1.upto(number-1) do |x|
results += x if x % 3 == 0 || x % 5 == 0
end
results
end
solution(number)
=begin
Best solutions on codewars
users: tanzeeb, pedantech, gdott9, owenbyrne, sdanthony, Darigaaz (plus 7 more warriors)
def solution(number)
(1...number).select {|i| i%3==0 || i%5==0}.inject(:+)
end
user: moser
def solution(number)
(1...number).select{|n| (n % 5).zero? || (n % 3).zero?}.reduce(:+)
end
=end
| true |
b5405a94708767ee1df6311025e392e706d547d0 | Ruby | shanebarringer/battle_royal | /lib/battle_royal/game.rb | UTF-8 | 3,156 | 3.625 | 4 | [
"MIT"
] | permissive | require_relative 'player'
require_relative 'roll'
require_relative 'weapon_chest'
require_relative 'lame_player'
require_relative 'advantaged_player'
require 'csv'
module BattleRoyal
class Game
attr_accessor :title, :players, :toasty
def initialize(title)
@title = title
@players = [].sort
@total_points = 0
@toasty = []
end
def add_player(player)
@players << player
end
def load_players(some_file)
CSV.foreach(some_file).each do |line|
add_player(Player.from_csv(line))
end
end
def save_high_scores
File.open("#{title}.txt", 'w') do |file|
file.puts "#{@title} High Scores:"
@players.sort_by(&:score).reverse_each do |player|
file.puts sort_and_score(player)
end
end
end
def start_of_game
puts "There are #{@players.size} players and #{WeaponChest::WEAPONS.count} weapons available in this game: "
WeaponChest::WEAPONS.each { |x| puts "A #{x.name} is worth #{x.points} points" }
end
def attack_player
@players.sample
end
def fatality?(player)
player.health < 0
end
def play(rounds)
start_of_game
1.upto(rounds) do
# if a block is given AND the block returns true, break out of loop.
break if yield if block_given?
if @players.count > 1
@players.shuffle.each do |player|
if !fatality?(player)
Roll.turn(player)
sleep(0.5)
player.attack(attack_player, player.found_weapon(Roll.weapon(player)))
sleep(0.5)
player.points
elsif fatality?(player)
@toasty << @players.find { |x| x == player }
puts "\n#{player.name} is no longer with us"
@players.delete(player)
sleep(0.5)
end
end
else
puts "\n#{@players[0].name.upcase} IS THE LAST MAN STANDING!!! "
break
end
end
@players |= @toasty
end
def print_player_and_health(criteria)
criteria.sort_by(&:score).reverse_each do |player|
puts "\n#{player.name}'s point totals: "
player.each_found_weapon do |weapon|
puts "#{weapon.points} total #{weapon.name} points"
end
puts "#{player.points} grand total points"
puts "health: #{player.health}"
end
end
def result
stronger, weaker = @players.partition(&:strong?)
puts "\n Statistics:"
puts "\n#{stronger.size} strong players:"
print_player_and_health(stronger)
puts "\n#{weaker.size} weaker players:"
print_player_and_health(weaker)
puts "\n#{total_points} total points for this match"
end
def winning
puts "\nScoreboard: "
@players.sort_by(&:score).reverse_each do |player|
puts sort_and_score(player)
end
end
def sort_and_score(player)
formatted_name = player.name.ljust(20, '.')
"#{formatted_name} #{player.score}"
end
def total_points
@players.inject(0) { |sum, player| sum + player.points }
end
end
end
| true |
b562f8136eee734be6cdcfb2e182077fcb0dd696 | Ruby | tank-bohr/pong | /lib/pong/game.rb | UTF-8 | 2,829 | 3.234375 | 3 | [] | no_license | require 'aasm'
require 'pong/player'
require 'pong/position'
require 'pong/ball'
module Pong
class Game
include AASM
aasm do
state :idle, initial: true
state :playing, :won, :loss
event :start, before: :bootstrap do
transitions from: :idle, to: :playing
end
event :win do
transitions from: :playing, to: :won
end
event :loose do
transitions from: :playing, to: :loss
end
end
attr_reader :width, :height, :state
attr_reader :beep, :pickup_coin
attr_reader :player_left, :player_right, :ball
def initialize(width:, height:)
@width = width
@height = height
@beep = Gosu::Sample.new("media/beep.wav")
@pickup_coin = Gosu::Sample.new("media/pickup_coin.wav")
end
def bootstrap
player_y = height / 2 - Player::SIZE[:height] / 2
left_player_position = Position.new(
x: 0,
y: player_y
)
right_player_position = Position.new(
x: width - Player::SIZE[:width],
y: player_y
)
ball_position = Position.new(
x: width / 2 - Ball::SIZE[:width] / 2,
y: height / 2 - Ball::SIZE[:height] / 2
)
velocity = 10
@player_left = Player.new(self, position: left_player_position, velocity: velocity)
@player_right = Player.new(self, position: right_player_position, velocity: velocity)
@ball = Ball.new(
self,
position: ball_position,
# FIXME: randomize direction
direction: Position.new(x: 1, y: 1),
velocity: 2
)
end
def update
direction = get_direction
player_left.move(direction)
player_right.move(direction)
ball.move
end
def draw
player_left.draw
player_right.draw
ball.draw
end
def get_direction
if Gosu.button_down? Gosu::KB_UP
:up
elsif Gosu.button_down? Gosu::KB_DOWN
:down
end
end
def fits_y?(y)
(0 < y) && (y < height - Player::SIZE[:height])
end
def ball_collision(position)
if (0 > position.y) || (position.y > height - Ball::SIZE[:height])
pickup_coin.play
:vertical
elsif left_player_collision?(position) || right_player_collision?(position)
beep.play
:horizontal
elsif out?(position)
# Gosu::Sample.new("media/explosion.wav").play
exit
end
end
def left_player_collision?(position)
(Player::SIZE[:width] >= position.x) && player_left.catch?(position.y)
end
def right_player_collision?(position)
(width - Player::SIZE[:width] <= position.x + Ball::SIZE[:width]) \
&& player_right.catch?(position.y)
end
def out?(position)
(position.x < 0) || (position.x > width)
end
end
end
| true |
073b23667bee517634b7c7f4a9cfb1aa394b2aac | Ruby | Part1nax777/BlackJack | /player.rb | UTF-8 | 758 | 3.546875 | 4 | [] | no_license | require_relative 'validator'
require_relative 'hand'
require_relative 'bank'
class Player
include Validate
attr_accessor :name, :score, :bank, :hand
MSG_INCORRECT_NAME = 'You must input name'.freeze
def initialize(name)
@name = name
@bank = Bank.new
@bank.set_start_amount
@score = 0
validate!
@hand = Hand.new
end
def can_start_game?
@bank.money >= Bank::BET
end
def take_cards(deck, count = 1)
@hand.cards += deck.take_card(count)
end
def fold_cards
@hand.cards = []
end
def points
@hand.points
end
def give_money(amount)
@bank.put_money(amount)
end
def make_bet
@bank.bet
end
private
def validate!
raise MSG_INCORRECT_NAME if name == '' || nil
end
end
| true |
f51a335092a82752e1391a7a2f103a56005bbfdb | Ruby | jeffmbellucci/Assessments | /assessment02-retake/lib/board.rb | UTF-8 | 1,286 | 3.40625 | 3 | [] | no_license | require_relative 'card'
require_relative 'foundation'
require_relative 'move_error'
require_relative 'pile'
class Board
attr_reader :foundations, :piles
def self.deal(deck)
foundations = {}
Card.suits.each { |suit| foundations[suit] = Foundation.new(suit) }
piles = Array.new(7) { |i| Pile.deal(i, deck) }
Board.new(foundations, piles)
end
def initialize(foundations, piles)
@foundations = foundations
@piles = piles
end
def perform_drag(from_pile_num, num_cards, to_pile_num)
from_pile, to_pile = @piles[from_pile_num], @piles[to_pile_num]
high_card = from_pile.peek_take(num_cards).first
raise MoveError.new("invalid drag") unless to_pile.valid_move?(high_card)
to_pile.move(from_pile.take(num_cards))
end
def perform_promote(from_pile_num)
from_pile = @piles[from_pile_num]
card = from_pile.peek_take(1).first
foundation = @foundations[card.suit]
raise MoveError.new("invalid promote") unless foundation.valid_move?(card)
foundation.move(from_pile.take(1).first)
end
def print
@foundations.values.each { |foundation| puts foundation.render }
@piles.each_with_index { |pile, i| puts "#{i}: #{pile.render}" }
end
def won?
@piles.all? { |pile| pile.count == 0 }
end
end
| true |
cd36136ff434dc768ac2d9f2f23a266660385764 | Ruby | framgia1023/rails-elearning-okudo-wataru | /app/models/word.rb | UTF-8 | 588 | 2.71875 | 3 | [] | no_license | class Word < ApplicationRecord
belongs_to :category
has_many :choices
validates :content, presence: true
validate :check_choice
has_many :lessons, through: :answers
has_many :answers
accepts_nested_attributes_for :choices
private
def check_choice
correct = choices.collect{ |item| item.correct || nil}.compact
if correct.size == 0
errors.add(:choices, "1 choice is better sir")
elsif correct.size > 1
errors.add(:choices, "1 choice")
end
end
end
# collect makes array for into {}
# |item| means block valiable
# item.correct return only true because true | true |
dd6aac6fa7253b84a024d947af3b066c4d4aeb2f | Ruby | nekonabesan/Fundamental-Programming | /lec008/fp08_03.rb | UTF-8 | 2,677 | 3.296875 | 3 | [] | no_license | require 'benchmark'
require 'bigdecimal'
require 'bigdecimal/util'
require '../modules/fp_module.rb'
#/===============================================================/
# 演習 3 モンテカルロ法で数値積分を行うときの、
# 精度 (有効桁数) と試行の数との関係について考察せよ。
# 円周率の例題を活用してもよいが、
# できれば別の関数を積分するプログラムを作って検討することが望ましい。
#/===============================================================/
def pirandom(n)
begin
raise ArgumentError if n.nil?
count = 0
n.times do
x = rand()
y = rand()
count = count + 1 if x**2 + y**2 < 1.0
end
return 4.0 * count / n
rescue => e
return e
end
end
#/===============================================================/
# テキストの回答例
# param int
# param floot
#/===============================================================/
def integrandom(n)
begin
raise ArgumentError if n.nil?
count = 0
n.times do
x = rand()
y = rand()
if y < x then
count = count + 1
end
end
return count / n.to_f
rescue => e
return e
end
end
#/===============================================================/
# モンテカルロ法/打点計数による1次元積分
# f(x) = -x^2+9
# param int
# return array
#/===============================================================/
def funcrand1(n)
begin
raise ArgumentError if n.nil?
cnt = 0
results = Array.new
n.times do
x = rand(-3.0...3.0)
y = rand(0.0...9.0)
if y <= (-1 * (x**2 - 9)) then
cnt += 1
end
end
result = ((1.0/n.to_f) * cnt.to_f * 54.0)
results.push(result)
if 36 < result then
results.push(result - 36)
else
results.push(36 - result)
end
return results
rescue => e
return e
end
end
#/===============================================================/
# モンテカルロ法/数値積分による1次元積分
# (参)https://rayspace.xyz/CG/contents/montecarlo/
# f(x) = -x^2+9
# param int
# return array
#/===============================================================/
def funcrand2(n)
begin
raise ArgumentError if n.nil?
cnt = 0
results = Array.new
result = 0;
intnum = 0;
n.times do
x = rand(-3.0...3.0)
y = rand(0.0...9.0)
intnum += (-1 * (x**2 - 9))
end
result = (6.0/n.to_f) * intnum.to_f
results.push(result)
if 36 < result then
results.push(result - 36.0)
else
results.push(36.0 - result)
end
return results
rescue => e
return e
end
end
| true |
85b82a504af17b5f4685f0e06e28be6793c376e8 | Ruby | vngrv/ruby-game-of-life | /lib/game.rb | UTF-8 | 323 | 3.125 | 3 | [] | no_license | require_relative 'cell'
require_relative 'board'
class Game
def call(width, height, cell, cells = [], fps = 0.1)
system('clear')
board = Board.new(width, height, cell, cells)
puts board
until board.lifeness?
board.evolve
sleep fps
system('clear')
puts board
end
end
end
| true |
09013a4fb36c3989f837139c5be2de76b4dae10c | Ruby | spatchcock/quantify | /spec/quantify/quantity_spec.rb | UTF-8 | 29,049 | 3.1875 | 3 | [
"MIT"
] | permissive | # encoding: UTF-8
require 'spec_helper'
describe Quantity do
describe "#initialize" do
specify { Quantity.new(1).should eq(Quantity.new(1,'unity')) }
specify { Quantity.new(nil,nil).should eq(Quantity.new(nil,'unity')) }
specify { Quantity.new(nil,nil).should eq(Quantity.new(nil,'unity')) }
specify { Quantity.new(nil,'unity').should eq(Quantity.new(nil,'unity')) }
specify { Quantity.new(nil).should eq(Quantity.new(nil,'unity')) }
end
it "should fail fast on invalid value input" do
expect{ Quantity.new('invalid', 'kg') }.to raise_error ArgumentError
end
it "should fail fast on invalid value assignment" do
quantity = Quantity.new(10, 'kg')
expect{ quantity.value = 'invalid' }.to raise_error ArgumentError
end
it "should fail fast on invalid unit input" do
expect{ Quantity.new(1, 'invalid unit') }.to raise_error Quantify::Exceptions::InvalidUnitError
end
it "should fail fast on invalid unit assignment" do
quantity = Quantity.new(10, 'kg')
expect{ quantity.unit = 'invalid unit' }.to raise_error Quantify::Exceptions::InvalidUnitError
end
it "should create a valid instance with nil values" do
quantity = Quantity.new nil
quantity.value.should be_nil
quantity.unit.should == (Unit.for('unity'))
end
it "should create a dimensionless quantity" do
quantity = Quantity.new 100
quantity.value.should eql 100.0
quantity.unit.is_dimensionless?.should be_true
quantity.to_s.should eql "100.0"
end
it "sets value to nil" do
quantity = Quantity.new 100, 'kg'
quantity.value.should eq(100)
quantity.value = nil
quantity.value.should be_nil
end
it "sets unit to unity when assigned nil" do
quantity = Quantity.new 100, 'kg'
quantity.unit.should eq(Unit.for('kg'))
quantity.unit = nil
quantity.unit.should eq(Unit.for(:unity))
end
it "should create a valid instance with standard create and unit name" do
quantity = Quantity.new 10.0, 'metre'
quantity.value.should == 10
quantity.unit.symbol.should == 'm'
end
it "should create a valid instance with standard create and unit name" do
quantity = Quantity.new 5000, :kilowatt
quantity.value.should == 5000
quantity.unit.symbol.should == 'kW'
end
it "should create a valid instance with standard create and unit symbol" do
quantity = Quantity.new 5000, 'kW'
quantity.value.should == 5000
quantity.unit.name.should == 'kilowatt'
end
it "should create a valid instance with dynamic create and unit name" do
quantity = 10.metre
quantity.value.should == 10
quantity.unit.symbol.should == 'm'
end
it "should create a valid instance with dynamic create and unit symbol" do
quantity = 10.km
quantity.value.should == 10
quantity.unit.name.should == 'kilometre'
end
it "should create valid instances with class parse method" do
quantities = Quantity.parse "10m driving and 5 tonnes carried"
quantities.should be_a Array
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'm'
quantities.last.value.should == 5
quantities.last.unit.symbol.should == 't'
end
it "should create a valid instance with class parse method" do
quantities = Quantity.parse "10 m"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'm'
end
it "should create a valid instance with class parse method" do
quantities = Quantity.parse "155.6789 ly"
quantities.first.value.should == 155.6789
quantities.first.unit.name.should == 'light year'
quantities.first.represents.should == 'length'
end
it "should create a valid instance with class parse method and per unit with symbols" do
quantities = Quantity.parse "10 m / h"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'm/h'
end
it "should create a valid instance with class parse method and per unit with names" do
quantities = Quantity.parse "10 miles / hour"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'mi/h'
end
it "should create a valid instance with class parse method and compound per unit with names" do
quantities = Quantity.parse "10 kilograms / tonne kilometre"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'kg/t km'
end
it "should create a valid instance with class parse method and compound per unit with symbols" do
quantities = Quantity.parse "10 kg / t km"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'kg/t km'
end
it "should create a valid instance from complex string with compound per unit" do
quantities = Quantity.parse "We sent some freight 6000 nautical miles by ship and the emissions rate was 10 kg / t km"
quantities.first.value.should == 6000
quantities.first.unit.name.should == 'nautical mile'
quantities.first.unit.symbol.should == 'nmi'
quantities[1].value.should == 10
quantities[1].unit.pluralized_name.should == 'kilograms per tonne kilometre'
quantities[1].unit.symbol.should == 'kg/t km'
end
it "should create a valid instance from complex string with compound per unit and no spaces" do
quantities = Quantity.parse "We sent some freight 6000 nautical miles by ship and the emissions rate was 10 kg/t km"
quantities.first.value.should == 6000
quantities.first.unit.name.should == 'nautical mile'
quantities.first.unit.symbol.should == 'nmi'
quantities[1].value.should == 10
quantities[1].unit.pluralized_name.should == 'kilograms per tonne kilometre'
quantities[1].unit.symbol.should == 'kg/t km'
end
it "should create valid instances from complex string" do
quantities = Quantity.parse "I travelled 220 miles driving my car and using 0.13 UK gallons per mile of diesel"
quantities.first.value.should == 220
quantities.first.unit.name.should == 'mile'
quantities.first.unit.symbol.should == 'mi'
quantities[1].value.should == 0.13
quantities[1].unit.pluralized_name.should == 'UK gallons per mile'
quantities[1].unit.symbol.should == 'gal/mi'
end
it "should create valid instances from easy string" do
quantities = Quantity.parse "100km"
quantities.first.value.should == 100
quantities.first.unit.name.should == 'kilometre'
end
it "should create a valid instance with unity unit from an empty string" do
quantities = Quantity.parse " "
quantities.first.value.should == nil
quantities.first.unit.name.should == ''
end
it "should create valid instances from complex string, no space and two-digit symbol" do
quantities = Quantity.parse "100km driving cars"
quantities.first.value.should == 100
quantities.first.unit.name.should == 'kilometre'
end
it "should create valid instances from complex string with punctuation" do
quantities = Quantity.parse "66666 kg; 5 lb; 86 gigagrams per kelvin and some more words"
quantities.first.value.should == 66666
quantities.first.unit.name.should == 'kilogram'
quantities[1].value.should == 5
quantities[1].unit.pluralized_name.should == 'pounds'
quantities[1].unit.symbol.should == 'lb'
quantities[2].value.should == 86
quantities[2].unit.pluralized_name.should == 'gigagrams per kelvin'
quantities[2].unit.symbol.should == 'Gg/K'
end
it "should create valid instances from complex string with punctuation" do
quantities = Quantity.parse "6 kilogram square metre per second^2"
quantities.first.value.should == 6
quantities.first.unit.name.should == 'kilogram square metre per square second'
end
it "should create valid instances from complex string with punctuation" do
quantities = Quantity.parse "I make 1 cup of tea with 1 tea bag, 0.3 litres of water, 10 g of sugar and 1 dram of milk"
quantities.first.value.should == 1
quantities.first.unit.name.should == 'cup'
quantities[1].value.should == 1
quantities[1].unit.name.should == ''
quantities[2].value.should == 0.3
quantities[2].unit.name.should == 'litre'
quantities[3].value.should == 10
quantities[3].unit.name.should == 'gram'
quantities[4].value.should == 1
quantities[4].unit.name.should == 'dram'
end
it "should create valid instances from complex string with indices" do
quantities = Quantity.parse "I sprayed 500 litres of fertilizer across 6000 m^2 of farmland"
quantities.first.value.should == 500
quantities.first.unit.name.should == 'litre'
quantities.first.unit.symbol.should == 'L'
quantities[1].value.should == 6000
quantities[1].unit.pluralized_name.should == 'square metres'
quantities[1].unit.symbol.should == 'm²'
end
it "should create valid instance from string with 'square' prefix descriptor" do
quantities = Quantity.parse "25 square feet"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'square foot'
quantities.first.unit.symbol.should == 'ft²'
end
it "should create valid instance from string with 'cubic' prefix descriptor" do
quantities = Quantity.parse "25 cubic feet"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'cubic foot'
quantities.first.unit.symbol.should == 'ft³'
end
it "should create valid instance from string with 'squared' suffix descriptor" do
quantities = Quantity.parse "25 feet squared"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'square foot'
quantities.first.unit.symbol.should == 'ft²'
end
it "should return dimensionless quantity when 'squared' suffix used without a unit" do
quantities = Quantity.parse "25 squared"
quantities.first.value.should == 25
quantities.first.unit.name.should == ''
quantities.first.unit.symbol.should == ''
end
it "should return unsquared quantity when 'squared' suffix used unrelated to unit" do
quantities = Quantity.parse "25 grams some more text and then squared"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'gram'
quantities.first.unit.symbol.should == 'g'
end
it "should return unsquared quantity when 'square' suffix used" do
quantities = Quantity.parse "25 grams square"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'gram'
quantities.first.unit.symbol.should == 'g'
end
it "should return dimensionless quantity when 'square' prefix used without a unit" do
quantities = Quantity.parse "25 square"
quantities.first.value.should == 25
quantities.first.unit.name.should == ''
quantities.first.unit.symbol.should == ''
end
it "should return dimensionless quantity when 'cubed' suffix used without a unit" do
quantities = Quantity.parse "25 cubed"
quantities.first.value.should == 25
quantities.first.unit.name.should == ''
quantities.first.unit.symbol.should == ''
end
it "should return dimensionless quantity when 'cubic' prefix used without a unit" do
quantities = Quantity.parse "25 cubic"
quantities.first.value.should == 25
quantities.first.unit.name.should == ''
quantities.first.unit.symbol.should == ''
end
it "should create valid instance from string with 'cubed' suffix descriptor" do
quantities = Quantity.parse "25 feet cubed"
quantities.first.value.should == 25
quantities.first.unit.name.should == 'cubic foot'
quantities.first.unit.symbol.should == 'ft³'
end
it "should create valid instances from complex string with no spaces" do
quantities = Quantity.parse "I sprayed 500L of fertilizer across 6000m^2 of farmland"
quantities.first.value.should == 500
quantities.first.unit.name.should == 'litre'
quantities.first.unit.symbol.should == 'L'
quantities[1].value.should == 6000
quantities[1].unit.pluralized_name.should == 'square metres'
quantities[1].unit.symbol.should == 'm²'
end
it "should create a valid instance with class parse method and per unit" do
quantities = Quantity.parse "10 miles / hour"
quantities.first.value.should == 10
quantities.first.unit.symbol.should == 'mi/h'
end
it "should create a valid instance with class parse method and return remainders" do
quantities = Quantity.parse "I sprayed 500L of fertilizer across 6000m^2 of farmland", :remainder => true
quantities.first.should be_a Array
quantities.first[0].value.should == 500
quantities.first[0].unit.name.should == 'litre'
quantities.first[0].unit.symbol.should == 'L'
quantities.first[1].value.should == 6000
quantities.first[1].unit.pluralized_name.should == 'square metres'
quantities.first[1].unit.symbol.should == 'm²'
quantities[1].should be_a Array
quantities[1].size.should eql 3
quantities[1][0].should eql "I sprayed"
quantities[1][1].should eql "of fertilizer across"
quantities[1][2].should eql "of farmland"
end
it "should parse using string method" do
"20 m".to_q.first.value.should == 20.0
"45.45 BTU".to_q.first.class.should == Quantity
"65 kilometres per hour".to_q.first.unit.class.should == Unit::Compound
end
it "should create a valid instance with class parse method based on to_string method" do
quantity_1 = Quantity.new 15, :watt
quantity_2 = Quantity.parse quantity_1.to_s
quantity_2.first.value.should == 15
quantity_2.first.unit.name.should == 'watt'
quantity_2.first.represents.should == 'power'
end
it "should create a valid instance with class parse method and unit prefix based on to_string method" do
quantity_1 = Quantity.new 15, :watt
quantity_2 = Quantity.parse quantity_1.to_s
quantity_2.first.value.should == 15
quantity_2.first.unit.name.should == 'watt'
quantity_2.first.represents.should == 'power'
end
it "should convert quantity correctly" do
1.km.to_metre.unit.symbol.should == 'm'
1.km.to_metre.to_s.should == "1000.0 m"
end
it "should convert quantity correctly" do
1.BTU.to_joule.to_s.should == "1054.804 J"
end
it "should convert quantity correctly" do
1.hour.to_second.to_s.should == "3600.0 s"
end
it "should convert quantity correctly with scaling (temperature)" do
85.degree_farenheit.to_degree_celsius.round.to_s.should == "29 °C"
end
it "should convert quantity correctly with scaling (temperature) and with decimal places" do
85.degree_farenheit.to_degree_celsius.round(2).to_s.should == "29.44 °C"
end
it "should add quantities correctly with same units" do
(5.metre + 3.metre).to_s.should == "8.0 m"
end
it "should add quantities correctly with same units" do
(125.4.kelvin + 61.3.K).to_s.should == "186.7 K"
end
it "should add quantities correctly with different units of same dimension" do
(15.foot + 5.yd).to_s.should == "30.0 ft"
end
it "should add quantities correctly with different units of same dimension" do
(125.4.kelvin + -211.85.degree_celsius).to_s.should == "186.7 K"
end
it "should throw error when adding quantities with different dimensions" do
lambda{1.metre + 5.kg}.should raise_error
end
it "should throw error when adding nil quantities" do
lambda{Quantity.new(nil,nil) + 5.kg}.should raise_error
end
it "should subtract quantities correctly with different units of same dimension" do
result = (125.4.kelvin - -211.85.degree_celsius)
result.value.should be_within(0.00000001).of(64.1)
result.unit.symbol.should == "K"
end
it "should subtract quantities correctly with different units of same dimension" do
(300.foot - 50.yard).round.to_s.should == "150 ft"
end
it "should subtract quantities correctly with same units" do
(300.foot - 100.ft).round.to_s.should == "200 ft"
end
it "should throw error when subtracting quantities with different dimensions" do
lambda{1.metre - 5.kg}.should raise_error
end
it "should throw error when subtracting nil quantities" do
lambda{Quantity.new(nil,nil) - 5.kg}.should raise_error
end
it "should successfully multiply a quantity by a scalar" do
(20.metre * 3).to_s.should == "60.0 m"
end
it "should successfully multiply a quantity by a scalar" do
(2.kg * 50).round.to_s.should == "100 kg"
end
it "should raise error if multiplying by string" do
lambda{20.metre * '3'}.should raise_error
end
it "should raise error when multiplying by nil quantity" do
lambda{Quantity.new(nil,nil) * 5.kg}.should raise_error
lambda{5.kg * Quantity.new(nil,nil)}.should raise_error
end
it "should multiply two quantities" do
quantity = (20.metre * 1.metre)
quantity.value.should == 20
quantity.unit.measures.should == 'area'
end
it "should successfully divide a quantity by a scalar" do
(20.metre / 5).to_s.should == "4.0 m"
end
it "should throw ZeroDivisionError error when dividing a quantity by '0'" do
lambda{2.kg / 0}.should raise_error ZeroDivisionError
end
it "should NOT throw ZeroDivisionError error when multiplying a quantity by '0'" do
lambda{2.kg * 0}.should_not raise_error ZeroDivisionError
end
it "should multiply a quantity by '0'" do
(2.kg * 0).to_s.should == "0.0 kg"
end
it "should successfully divide a quantity by a scalar" do
(2.kg / 0.5).round.to_s.should == "4 kg"
end
it "should throw error when dividing nil quantities" do
lambda{Quantity.new(nil,nil) / 5.kg}.should raise_error
lambda{5.kg / Quantity.new(nil,nil)}.should raise_error
end
it "should calculate speed from distance and time quantities" do
distance_in_km = 12.km
time_in_min = 16.5.min
distance_in_miles = distance_in_km.to_miles
time_in_hours = time_in_min.to_hours
speed = distance_in_miles / time_in_hours
speed.class.should == Quantity
# use #be_within to tolerate Ruby 1.8.7 - 1.9.2 differences
speed.value.should be_within(1.0e-08).of(27.1143792976291)
speed.unit.pluralized_name.should eql "miles per hour"
end
it "coerce method should handle inverted syntax" do
quantity = 1/2.ft
quantity.to_s.should == "0.5 ft^-1"
quantity.to_s(:name).should == "0.5 per foot"
end
it "should convert temperature correctly" do
30.degree_celsius.to_K.to_s.should == "303.15 K"
end
it "should convert temperature correctly" do
30.degree_celsius.to_degree_farenheit.round.to_s.should == "86 °F"
end
it "should convert standard units correctly" do
27.feet.to_yards.round.to_s(:name).should == "9 yards"
end
it "should convert standard units correctly" do
quantity = 6000.BTU.to_megajoules
# use #be_within to tolerate Ruby 1.8.7 - 1.9.2 differences
quantity.value.should be_within(1.0e-08).of(6.328824)
quantity.unit.pluralized_name.should eql "megajoules"
end
it "should convert standard units correctly" do
quantity = 13.1.stones.to_kg
# use #be_within to tolerate Ruby 1.8.7 - 1.9.2 differences
quantity.value.should be_within(1.0e-08).of(83.1888383)
quantity.unit.pluralized_name.should eql "kilograms"
end
specify "converting a nil quantity to another unit yields nil" do
lambda{ Quantity.new(nil,nil).to_kg }.should raise_error
end
specify "converting a quantity to an incompatible unit raises error" do
lambda{ Quantity.new(20,:yd).to_kg }.should raise_error
end
it "should raise error when trying to round a nil quantity" do
lambda{Quantity.new(nil,nil).round(2)}.should raise_error
end
it "should convert compound units correctly" do
speed = Quantity.new 100, (Unit.km/Unit.h)
speed.to_mi.round(2).to_s.should == "62.14 mi/h"
end
specify "#to_si is non-destructive" do
q1 = Quantity.new(100,'mm')
q1.to_si.equal?(q1).should be_false
q1.value.should eq(100)
q1.unit.symbol.should eq('mm')
q2 = Quantity.new(nil,'mm')
q2.to_si.equal?(q2).should be_false
q2.value.should be_nil
q2.unit.symbol.should eq('mm')
q3 = Quantity.new(100)
q3.to_si.equal?(q3).should be_false
q3.value.should eq(100)
q3.unit.symbol.should eq('')
end
it "should convert to SI unit correctly" do
100.cm.to_si.to_s.should == "1.0 m"
quantity = 2.kWh.to_si
# use #be_within to tolerate Ruby 1.8.7 - 1.9.2 differences
quantity.value.should be_within(1.0e-08).of(7200000.0)
quantity.unit.symbol.should eql "J"
400.ha.to_si.to_s.should == "4000000.0 m²"
35.degree_celsius.to_si.to_s.should == "308.15 K"
end
it "should convert compound units to SI correctly" do
speed = Quantity.new 100, (Unit.mi/Unit.h)
speed.to_si.to_s(:name).should == "44.704 metres per second"
end
it "should convert dimensionless units to SI identity operation" do
unity_quantity = Quantity.new 100
unity_quantity.to_si.should eq(unity_quantity)
end
it "should convert quantities with nil values to SI" do
nil_quantity = Quantity.new nil, 'mV'
nil_quantity.to_si.should eq(Quantity.new(nil, 'V'))
end
it "should convert compound units to SI correctly" do
speed = Quantity.new 100, (Unit.km/Unit.h)
speed.to_si.value.should be_within(0.0000000000001).of(27.7777777777778)
speed.to_si.unit.name.should == "metre per second"
end
it "should convert compound units to SI correctly" do
pressure = Quantity.new 100, (Unit.pound_force_per_square_inch)
pressure.to_si.round.to_s(:name).should == "689476 pascals"
end
it "should return equivalent unit according to specification" do
(50.square_metres/10.m).to_s.should == "5.0 m"
(1.kg*20.m*2.m/4.s/5.s).to_s(:name).should == '2.0 joules'
(80.kg/2.m/4.s/5.s).to_s(:name).should == '2.0 pascals'
end
it "should raise error when trying to raise a nil quantity to a power" do
lambda{Quantity.new(nil,nil) ** 2}.should raise_error
lambda{Quantity.new(nil,nil).pow(2)}.should raise_error
end
it "should raise a quantity to a power correctly" do
unit = 50.ft ** 2
unit.to_s.should == "2500.0 ft²"
unit = 50.ft ** 3
unit.to_s.should == "125000.0 ft³"
unit = 50.ft ** -1
unit.to_s.should == "0.02 ft^-1"
unit = (10.m/1.s)**2
unit.to_s.should == "100.0 m²/s²"
unit = (10.m/1.s)**-1
unit.to_s.should == "0.1 s/m"
lambda{ ((10.m/1.s)** 0.5) }.should raise_error
end
it "should raise a quantity to a power correctly" do
(50.ft.pow! 2).to_s.should == "2500.0 ft²"
(50.ft.pow! 3).to_s.should == "125000.0 ft³"
(50.ft.pow! -1).to_s.should == "0.02 ft^-1"
((10.m/1.s).pow! 2).to_s.should == "100.0 m²/s²"
((10.m/1.s).pow! -1).to_s.should == "0.1 s/m"
lambda{ ((10.m/1.s).pow! 0.5) }.should raise_error
end
it "should cancel by base units of original compound unit if necessary" do
quantity = Quantity.new(20, Unit.psi).to(Unit.inches_of_mercury)
quantity.unit.base_units.size.should == 1
# use #be_within to tolerate Ruby 1.8.7 - 1.9.2 differences
quantity.value.should be_within(1.0e-08).of(40.720412743579)
quantity.unit.symbol.should eql "inHg"
end
it "should rationalize units and return new quantity" do
quantity = 12.yards*36.feet
quantity.to_s.should eql "432.0 yd ft"
new_quantity=quantity.rationalize_units
quantity.to_s.should eql "432.0 yd ft"
new_quantity.value.should be_within(0.0000001).of(144)
new_quantity.unit.symbol.should eql "yd²"
end
it "should rationalize units and modify value in place" do
quantity = 12.yards*36.feet
quantity.to_s.should eql "432.0 yd ft"
quantity.rationalize_units!
quantity.value.should be_within(0.0000001).of(144)
quantity.unit.symbol.should eql "yd²"
end
context "comparing nil quantities" do
context "when comparing with non-nil quantities" do
specify "greater than" do
lambda{Quantity.new(nil,nil) > 1.m}.should raise_error
end
specify "greater than or equals" do
lambda{Quantity.new(nil,nil) >= 1.m}.should raise_error
end
specify "less than" do
lambda{Quantity.new(nil,nil) < 1.m}.should raise_error
end
specify "less than or equals" do
lambda{Quantity.new(nil,nil) <= 1.m}.should raise_error
end
specify "equals" do
lambda{Quantity.new(nil,nil) == 1.m}.should raise_error
end
specify "between" do
lambda{Quantity.new(nil,nil).between? 1.ft,10.m}.should raise_error NoMethodError
lambda{Quantity.new(nil,nil).between? Quantity.new(nil,nil),Quantity.new(nil,nil)}.should raise_error NoMethodError
end
specify "range" do
expect{(Quantity.new(nil)..1.kg)}.to raise_error
expect{(1.kg..Quantity.new(nil))}.to raise_error
end
end
context "when comparing with another nil quantity" do
specify "greater than" do
(Quantity.new(nil) > Quantity.new(nil)).should be_false
end
specify "greater than or equals" do
(Quantity.new(nil) >= Quantity.new(nil)).should be_true
end
specify "less than" do
(Quantity.new(nil) < Quantity.new(nil)).should be_false
end
specify "less than or equals" do
(Quantity.new(nil) <= Quantity.new(nil)).should be_true
end
specify "equals" do
(Quantity.new(nil) == Quantity.new(nil)).should be_true
end
specify "range" do
(Quantity.new(nil)..Quantity.new(nil)).should eq(Quantity.new(nil,'unity')..Quantity.new(nil, 'unity'))
end
end
end
it "should be greater than" do
(20.ft > 1.m).should be_true
end
it "should be greater than" do
(20.ft > 7.m).should be_false
end
it "should be less than" do
(20.ft/1.h < 8.yd/60.min).should be_true
end
it "should be equal" do
(1.yd == 3.ft).should be_true
end
it "should be between with same units" do
(25.ft.between? 1.ft,30.ft).should be_true
end
it "should be between even with different units" do
(25.ft.between? 1.ft,10.m).should be_true
end
it "comparison with non quantity should raise error" do
lambda{20.ft > 3}.should raise_error
end
it "comparison with non compatible quantity should raise error" do
lambda{20.ft > 4.K}.should raise_error
end
it "should be range" do
(2.ft..20.ft).should be_a Range
end
it "should return between value from range" do
(2.ft..20.ft).cover?(3.ft).should be_true
end
it "should return between value from range with different units" do
(2.ft..4.m).cover?(200.cm).should be_true
(1.ly..1.parsec).cover?(2.ly).should be_true
(1.ly..1.parsec).cover?(2.in).should be_false
end
it "should return between value from range using === operator" do
(3.ft === (2.ft..20.ft)).should be_true
end
it "should return between value from range with different units using === operator" do
(200.cm === (2.ft..4.m)).should be_true
(2.ly === (1.ly..1.parsec)).should be_true
(2.in === (1.ly..1.parsec)).should be_false
end
it "range comparison with non compatible quantity should raise error" do
lambda{20.ft === (1.ft..3.K)}.should raise_error
end
it "range comparison with non quantity should raise error" do
lambda{20.ft === (1.ft..3)}.should raise_error
end
specify "a range with one nil quantity raises an error" do
lambda{Quantity.new(nil)..20.ft}.should raise_error
end
specify "cover? with nil quantities raises an error" do
lambda{(2.ft..20.ft).cover?(Quantity.new(nil))}.should raise_error
end
it "should return unit consolidation setting" do
Quantity.auto_consolidate_units?.should be_false
end
it "should set unit consolidation setting" do
Quantity.auto_consolidate_units?.should be_false
Quantity.auto_consolidate_units=true
Quantity.auto_consolidate_units?.should be_true
Quantity.auto_consolidate_units=false
Quantity.auto_consolidate_units?.should be_false
end
it "should return non-consolidated units if consolidation disabled" do
quantity = 20.L * 1.km * (5.lb / 1.L)
quantity.to_s.should eql "100.0 L km lb/L"
end
it "should return equivalent units if consolidation disabled" do
quantity = 20.L * (5.lb / 1.L)
quantity.to_s.should eql "100.0 lb"
end
it "should return equivalent units if consolidation enabled" do
Quantity.auto_consolidate_units=true
quantity = 20.L * (5.lb / 1.L)
quantity.to_s.should eql "100.0 lb"
end
it "should return consolidated units if enabled" do
Quantity.auto_consolidate_units=true
quantity = 20.L * 1.km * (5.lb / 1.L)
quantity.to_s.should eql "100.0 km lb"
end
it "should clone unit instance if quantity cloned" do
quantity = 20.L
unit = quantity.unit
new_quantity = quantity.clone
# ensure distinct unit instances
new_quantity.unit.should_not eql(unit)
end
it "should clone unit instance if quantity dup" do
quantity = 20.L
unit = quantity.unit
new_quantity = quantity.dup
# ensure distinct unit instances
new_quantity.unit.should_not eql(unit)
end
end
| true |
686d927afbd08ffa41863df3d3ac932293965e24 | Ruby | rkstarnerd/tealeaf_intro_precourse_work | /flow_control_ex5.rb | UTF-8 | 414 | 4.5 | 4 | [] | no_license | puts "Enter a number between 0 and 100."
number = gets.chomp.to_i
def compare(number)
answer = case
when number > 0 && number <= 50
"#{number} is between 0 and 50."
when number > 50 && number <= 100
"#{number} is between 50 and 100."
when number > 100
"Doh! #{number} is greater than 100. Try again!"
else
"Doh! #{number} is less than or equal to 0. Try again!"
end
end
puts compare(number) | true |
fbf36b8ff5ec4f7ac4b4fbe0894ec5c80d90452b | Ruby | jamestunnell/music-instruments | /lib/music-instruments/instrument_key.rb | UTF-8 | 4,858 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Music
module Instruments
# The fundamental unit for performing notes.
class InstrumentKey
include Hashmake::HashMakeable
# defines how hashed args should be formed for initialization
ARG_SPECS = {
:sample_rate => arg_spec(:reqd => true, :type => Fixnum),
:inactivity_threshold => arg_spec(:reqd => false, :type => Float, :default => 1.0e-5),
:inactivity_timeout_sec => arg_spec(:reqd => true, :type => Float),
:pitch_range => arg_spec(:reqd => true, :type => Range, :validator => ->(a){ a.max > a.min }),
:start_pitch => arg_spec(:reqd => true),
:handler => arg_spec(:reqd => true, :validator => ->(handler){
return handler.respond_to?(:on) &&
handler.method(:on).arity == 3 &&
handler.respond_to?(:off) &&
handler.method(:off).arity == 0 &&
handler.respond_to?(:release) &&
handler.method(:release).arity == 1 &&
handler.respond_to?(:restart) &&
handler.method(:restart).arity == 3 &&
handler.respond_to?(:adjust) &&
handler.method(:adjust).arity == 1 &&
handler.respond_to?(:render) &&
handler.method(:render).arity == 1
}),
}
attr_reader :inactivity_threshold, :inactivity_timeout_sec, :sample_rate, :pitch_range, :start_pitch, :current_pitch, :handler
def initialize args
hash_make args, InstrumentKey::ARG_SPECS
check_pitch @start_pitch
@max_inactivity_samples = @inactivity_timeout_sec * @sample_rate
@current_inactivity_samples = 0
@current_pitch = @start_pitch
@active = false
end
# Return true if the key is active. Once activated (by calling #on), a key
# will remain active until it produces output below the inactivity threshold
# for duration of the inactivity timeout.
def active?
return @active
end
# Return true if the key has been released (by calling #release or #off).
def released?
return @released
end
# Activate the key (start playing the note).
#
# @param [Numeric] attack The intensity put into starting the note.
# @param [Numeric] sustain The desired level of sustain after starting the note.
# @param [Pitch] pitch The pitch to be used in playing the note.
def on(attack, sustain, pitch = @current_pitch)
@handler.on(attack,sustain,pitch)
activate
end
# Deactivate the key (stop playing the note altogether and at once).
def off
@handler.off
deactivate
end
# Restart a note that is already going.
#
# @param [Numeric] attack The intensity put into starting the note.
# @param [Numeric] sustain The desired level of sustain after starting the note.
# @param [Pitch] pitch The pitch to be used in playing the note.
#
# @raise [RuntimeError] if key is not active.
def restart(attack, sustain, pitch = @current_pitch)
unless active?
raise "Restarting is not allowed unless key is active"
end
@handler.restart(attack, sustain, pitch)
activate
end
# Adjust the pitch of a note that is already going.
#
# @param [Pitch] pitch The pitch to be used in playing the note.
#
# @raise [RuntimeError] if key is not active.
def adjust(pitch)
unless active?
raise "Adjsuting sustain is not allowed unless key is active"
end
check_pitch pitch
@handler.adjust(pitch)
@current_pitch = pitch
end
# Let the note die out according to the given damping rate.
#
# @param [Numeric] damping The damping rate to use in quieting the note.
#
# @raise [RuntimeError] if key is not active.
def release(damping)
unless active?
raise "Releasing is not allowed unless key is active"
end
@handler.release(damping)
@released = true
end
# Render the output of the note being played.
#
# @param [Fixnum] count The number of samples to render
#
# @raise [RuntimeError] if key is not active.
def render count
unless active?
raise "Rendering is not allowed unless key is active"
end
samples = @handler.render(count)
if released?
samples.each do |sample|
if sample < @inactivity_threshold
@current_inactivity_samples += 1
else
@current_inactivity_samples = 0
end
if @current_inactivity_samples >= @max_inactivity_samples
deactivate
end
end
end
return samples
end
# Make sure a pitch fits in the key's allowed range.
def check_pitch pitch
raise ArgumentError, "pitch is less than pitch range min" if pitch < @pitch_range.min
raise ArgumentError, "pitch is more than pitch range max" if pitch > @pitch_range.max
end
private
def activate
@active = true
@current_inactivity_samples = 0
@released = false
end
def deactivate
@active = false
@current_inactivity_samples = 0
@released = true
end
end
end
end
| true |
3d5eb8d1d8c1b652c8d2f6d82d7b9f2bd84efa16 | Ruby | mihir787/enigma | /test/encryptor_test.rb | UTF-8 | 1,662 | 2.859375 | 3 | [] | no_license | require_relative 'test_helper'
require_relative '../lib/encryptor'
class EncryptorTest < Minitest::Test
def setup
@test_file = File.new("test_file.txt", "w+")
@test_file.write("ruby is awesome")
@test_file.close
@test_file2 = File.new("test_file2.txt", "w+")
@test_file2.write("ruby is awesome 2")
@test_file2.close
@test_file3 = File.new("test_file3.txt", "w+")
@test_file3.close
end
def teardown
File.delete("test_file.txt")
File.delete("test_file2.txt")
File.delete("test_file3.txt")
end
def test_it_exists
assert Encryptor.new(@test_file, @test_file2)
end
def test_initializes_with_input_file_names
encryptor = Encryptor.new("file.txt", "file2.txt")
assert_equal "file.txt", encryptor.message_file_name
assert_equal "file2.txt", encryptor.encrypted_file_name
end
def test_it_can_encrypt
File.new("test_file4.txt", "w+")
encryptor = Encryptor.new("test_file.txt", "test_file4.txt")
encryptor.key = %w(1 5 9 3 0)
encryptor.encrypt("031015")
assert_equal "6dsum496pfvo38v", File.open("test_file4.txt").read
end
def test_it_can_encrypt_another_file
encryptor = Encryptor.new("test_file2.txt", "test_file3.txt")
encryptor.key = %w(9 9 9 4 0)
encryptor.encrypt("031115")
assert_equal ",et4s5 dvgwy99wdk", File.open("test_file3.txt").read
end
def test_it_can_encrypt_empty_message_by_returing_empty_file
File.new("test_file4.txt", "w+")
encryptor = Encryptor.new("test_file3.txt", "test_file4.txt")
encryptor.key = %w(0 0 9 3 0)
encryptor.encrypt("031015")
assert File.open("test_file4.txt").read.empty?
end
end
| true |
7e4cd772bdfcc50bfc6774c0a8305210193b62ca | Ruby | viveksraghuwanshi/test | /unless.rb | UTF-8 | 79 | 2.765625 | 3 | [] | no_license | #!/usr/bin/ruby -w
a=200
unless a > 100
print "#{a}";
else
print "100";
end
| true |
a62359c741e4a1f3352c80fa90cca16b079e4e27 | Ruby | drayas/PDHex | /app/models/game.rb | UTF-8 | 1,186 | 2.75 | 3 | [] | no_license | class Game < ActiveRecord::Base
has_many :game_users
has_many :users, :through => :game_users
# Players is an array of hashes with user_ids and deck_ids
#[
# {:user => u, :deck => d},
# {:user => u2, :deck => d1}
#]
def self.test
Game.start!([{:user => User.first, :deck => Deck.last}, {:user => User.last, :deck => Deck.last}])
end
def self.start!(players)
# Guard clauses
raise "Bad data structure!" unless players.is_a?(Array) && players.first.is_a?(Hash)
raise "Games require more than one player!" if players.size < 2
# Create our game
game = Game.create!
# We need to create game_decks for each player
user_names = []
players.each { |player|
raise "I need a player and deck for every player!" unless player[:user] && player[:deck]
game_user = GameUser.create!(
:game => game,
:user => player[:user]
)
user_names << player[:user].name
game_deck = GameDeck.create!(
:game_user => game_user,
:deck => player[:deck]
)
game_deck.prepare!
}
game.update_attribute(:name, "Game between #{user_names.join(" and ")}")
game
end
end
| true |
cc25e544dbd93c4930770312bde195f6b799746f | Ruby | hyphenized/c2-module2 | /week-2/day-1/howmuch.rb | UTF-8 | 1,258 | 3.40625 | 3 | [] | no_license | $input = <<doc
Category, (Symbol) Price, Stock, Amount, Name
Sporting Goods, USD 49.99, true, 10, Football
Sporting Goods, PEN 9.99, true, 3, Baseball
Sporting Goods, ARS 29.99, false, 0, Basketball
Electronics, PEN 99.99, true, 5, iPod Touch
Electronics, USD 399.99, false, 0, iPhone 5
Electronics, PEN 199.99, true, 2, Nexus 7
doc
# Transform it to an array of hashes and print out the total USD value of goods
# in stock, as well as the product with the most stock value in the storage.
RATES = {
USD: { PEN: 3, ARS: 40, USD: 1 },
}.freeze
def transform(input)
db = input.lines[1..-1].map do |line|
cat, price, stock, amount, name = line.split ', '
currency, value = price.split
{
cat: cat,
currency: currency.to_sym,
value: value.to_f,
stock: eval(stock),
amount: amount.to_i,
name: name.chomp,
}
end
usd = lambda { |value, currency| currency == :USD ? value : value / RATES.dig(:USD, currency) }
# most expensive product
costly = db.max_by { |item| item[:amount] * usd[item[:value], item[:currency]] }
# total
total = db.reduce(0) do |sum, entry|
sum + (entry[:stock] ? usd[entry[:value], entry[:currency]] * entry[:amount] : 0)
end
[costly, total]
end
p transform $input
| true |
339c1ba0c60606a179ae8f05784833404253b73f | Ruby | haletothewood/GildedRubyRose | /spec/item_spec.rb | UTF-8 | 604 | 3.203125 | 3 | [
"MIT"
] | permissive | require 'item'
describe Item do
name = 'Foo'
sell_in = 20
quality = 10
let(:item) { Item.new(name, sell_in, quality) }
describe '#new' do
it 'is created with a name' do
expect(item.name).to eq 'Foo'
end
it 'is created with a value for the number of days to sell within' do
expect(item.sell_in).to eq 20
end
it 'is created with a value for it\'s quality metric' do
expect(item.quality).to eq 10
end
end
describe '#to_string' do
it 'converts the items attributes to a string' do
expect(item.to_s).to eq "Foo, 20, 10"
end
end
end
| true |
156b6f6abf53d5f56077b1f7ad2b25ad1abb2409 | Ruby | istateside/minesweeper | /minesweeper.rb | UTF-8 | 5,115 | 3.53125 | 4 | [] | no_license | require 'yaml'
class Tile
NEIGHBOR_POS = [
[-1, -1],
[-1, 0],
[-1, 1],
[0, -1],
[0, 1],
[1, -1],
[1, 0],
[1, 1]
]
attr_accessor :is_bomb, :neighbors, :revealed, :is_flagged, :neighbor_bomb_count
attr_reader :board, :pos
def initialize(board, x, y)
@is_bomb = false
@neighbors = []
@revealed = false
@is_flagged = false
@neighbor_bomb_count = 0
@board = board
@pos = [x, y]
end
def is_bomb?
self.is_bomb
end
def get_neighbors
@neighbors = []
NEIGHBOR_POS.each do |(dx, dy)|
new_pos = [@pos[0] + dx, @pos[1] + dy]
if new_pos.all? { |coord| coord.between?(0,8) }
neighbors << @board[new_pos]
end
end
nil
end
def get_neighbor_bomb_count
get_neighbors
@neighbors.each do |neighbor|
@neighbor_bomb_count += 1 if neighbor.is_bomb?
end
end
def print_tile
# return a string depending on the state
return 'F' if @is_flagged
if @revealed
return 'B' if @is_bomb
@neighbor_bomb_count == 0 ? '_' : @neighbor_bomb_count
else
'*'
end
end
def flag_tile
@is_flagged = true
end
def reveal_tile
@revealed = true
if @is_bomb
return
elsif @neighbor_bomb_count == 0
unrevealed_neighbors = @neighbors.reject do |neighbor|
neighbor.revealed
end
unrevealed_neighbors.each { |neighbor| neighbor.reveal_tile }
end
nil
end
end
class Board
SIZE = 9
attr_reader :rows
def initialize
@rows = nil
end
def prepare_board
@rows = blank_grid
place_bombs
get_all_neighbor_bomb_counts
end
def place_bombs
@rows.flatten.sample(10).each { |tile| tile.is_bomb = true }
end
def get_all_neighbor_bomb_counts
@rows.flatten.each { |tile| tile.get_neighbor_bomb_count }
nil
end
def blank_grid
grid = Array.new(SIZE) { Array.new(SIZE) }
# grid = Array.new(SIZE) do |row_index|
# Array.new(SIZE) { |col_index| Tile.new }
# end
grid.each_with_index do |row, row_index|
col_index = 0
while col_index < row.length
row[col_index] = Tile.new(self, row_index, col_index)
col_index += 1
end
end
return grid
end
def [](pos)
x, y = pos[0], pos[1]
@rows[x][y]
end
def display
@rows.each do |row|
line = []
row.each { |tile| line << tile.print_tile }
puts line.join (' ')
end
nil
end
def flag_spot(pos)
if self[pos].nil? || self[pos].is_flagged
return false
else
self[pos].flag_tile
end
end
def reveal_spot(pos)
if self[pos].nil? || self[pos].revealed
return false
else
self[pos].reveal_tile
end
if self[pos].is_bomb
reveal_all_bombs
end
true
end
def reveal_all_bombs
@rows.each do |row|
row.each do |tile|
if tile.is_bomb
tile.revealed = true
tile.is_flagged = false
end
end
end
end
def loss?
@rows.each do |row|
#row.any? { |tile| tile.is_bomb && tile.revealed }
row.each do |tile|
if tile.is_bomb && tile.revealed
return true
end
end
end
false
end
def won?
@rows.all? do |row|
row.all? { |tile| tile.is_bomb ? next : tile.revealed }
end
end
end
class Game
def initialize
@board = Board.new
@board.prepare_board
end
def get_player_choice
# puts "Enter a command (f for flag, r for reveal) and a position (x,y)"
puts "Select a position. x,y"
input = gets.chomp
if input.downcase == 'save'
save_game
return
else
pos = input.split(',').map { |num| num.to_i }.reverse
end
# begin
# pos = Integer(num)
# rescue ArgumentError
# puts "Please put in valid move!!"
# retry
# end
if @board[pos].nil? || @board[pos].revealed
puts "Please enter valid coordinates."
return
end
puts "Flag (f) or reveal (r)?"
command = gets.chomp.downcase
if !['f','r', 'flag', 'reveal'].include?(command)
puts "Invalid move specified."
return
end
if ['r', 'reveal'].include?(command)
@board.reveal_spot(pos)
else
@board.flag_spot(pos)
end
end
def play
start_time = Time.now
loop do
@board.display
get_player_choice
break if @board.loss? || @board.won?
end
if @board.loss?
@board.display
puts "YOU LOSE."
puts "Time elapsed: #{Time.now - start_time}"
elsif @board.won?
@board.display
puts "You win!"
puts "Time elapsed: #{Time.now - start_time}"
end
end
def save_game
File.open("minesweeper_save.yaml", "w") do |file|
file.puts self.to_yaml
end
end
def self.load_game
loaded_game = YAML.load_file("minesweeper_save.yaml")
end
end
if __FILE__ == $PROGRAM_NAME
puts "Welcome to MINESWEEPER"
puts "NEW game or LOAD existing game (N or L)?"
user_input = gets.chomp.downcase
if user_input == 'n'
Game.new.play
else
Game.load_game.play
end
end
| true |
84bcb21882116a245dbc8fb5a5db4e2f274d6ac0 | Ruby | HakubJozak/pcdir-duben-2017 | /excersises/pi.rb | UTF-8 | 238 | 3.65625 | 4 | [] | no_license | require 'bigdecimal'
# Tayloruv rozvoj PI.
#
# Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
#
def sum(n)
s = BigDecimal.new("1")
sig = 1
1.upto(n) do |i|
sig *= -1
s += (1.0 / (2*i + 1)) * sig
end
4 * s
end
puts sum(30000000)
| true |
67379fc6df9105f460adb36fec88ba64b9a356ed | Ruby | armendarabyan/wordscollector | /app/filterwords.rb | UTF-8 | 592 | 2.828125 | 3 | [] | no_license | require './activerecord/words'
class FilterWords
def filter(words)
a = []
words.each do |word|
if not exist?(word)
a.push(word.downcase)
end
end
return a
end
def exist?(word)
Words.exists?(name: word.downcase)
end
def exist_in_unknown?(word)
Words.exists?(name: word.downcase, status:1)
end
def yes(word)
Words.create(name:word.downcase, status: 1)
end
def no(word)
Words.create(name:word.downcase, status: 0)
end
def showno
Words.where(status: 0)
end
def showyes
Words.where(status: 1)
end
end
| true |
c0d421d987ba5b3b2dcc316e44fd5175db6742d7 | Ruby | HariShankarS/exercism | /ruby/anagram/anagram.rb | UTF-8 | 337 | 3.09375 | 3 | [] | no_license | class Anagram
def initialize(word)
@word = word
end
def match(array)
output = []
array.each do |a|
unless a.downcase == @word.downcase
output << a if test(a) == test(@word)
end
end
output
end
def test(word)
word.downcase.chars.sort
end
end
module BookKeeping
VERSION = 2
end | true |
cd6b424e0221ad38a6f5cb6d86e53c634adc80d5 | Ruby | portco/connect_four | /spec/lib/connect_four/board_spec.rb | UTF-8 | 14,449 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
RSpec.describe ConnectFour::Board do
before :each do
@obj = ConnectFour::Board.new
end
context 'vertical_win? checking' do
it 'should return false with check vertical win due to minimal input' do
@obj.instance_variable_set(:@total_moves, 6)
expect(@obj.send(:vertical_win?)).to eq(false)
end
it 'should return true with vertical win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [2, 4])
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 5)
expect(@obj.send(:vertical_win?)).to eq(true)
end
it 'should return true with vertical win check with different board setting' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '1', '.', '2', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [1, 4])
@obj.instance_variable_set(:@total_moves, 9)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 5)
expect(@obj.send(:vertical_win?)).to eq(true)
end
it 'should return false with vertical win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.'],
['.', '.', '.', '2', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [2, 3])
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 4)
expect(@obj.send(:vertical_win?)).to eq(false)
end
end
context 'horizontal_win? checking' do
it 'should return false with check horizontal win due to minimal input' do
@obj.instance_variable_set(:@total_moves, 6)
expect(@obj.send(:horizontal_win?)).to eq(false)
end
it 'should return true with horizontal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '2', '2', '2', '.'],
['.', '.', '1', '1', '1', '1', '.']
]
player = ConnectFour::Player.new('Alice', 1, [5, 2])
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 3)
expect(@obj.send(:horizontal_win?)).to eq(true)
end
it 'should return true with vertical win check with different board setting' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '2', '.', '2', '2', '.', '.'],
['.', '1', '1', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [5, 2])
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 3)
expect(@obj.send(:horizontal_win?)).to eq(true)
end
it 'should return true with vertical win check with different board setting' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '2', '.', '2', '2', '.', '.'],
['.', '1', '.', '1', '1', '1', '.']
]
player = ConnectFour::Player.new('Alice', 1, [5, 5])
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 6)
expect(@obj.send(:horizontal_win?)).to eq(false)
end
end
context 'left_diagonal_win? checking' do
it 'should return false with check left diagonal win due to minimal input' do
@obj.instance_variable_set(:@total_moves, 10)
expect(@obj.send(:left_diagonal_win?)).to eq(false)
end
it 'should return true with left diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['1', '.', '.', '.', '.', '.', '.'],
['2', '1', '.', '.', '.', '.', '.'],
['2', '1', '1', '.', '.', '.', '.'],
['2', '2', '2', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [2, 0])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 1)
expect(@obj.send(:left_diagonal_win?)).to eq(true)
end
it 'should return true with left diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['1', '.', '.', '.', '.', '.', '.'],
['2', '1', '.', '.', '.', '.', '.'],
['2', '1', '1', '.', '.', '.', '.'],
['2', '2', '2', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [5, 3])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 4)
expect(@obj.send(:left_diagonal_win?)).to eq(true)
end
it 'should return true with left diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['1', '.', '.', '.', '.', '.', '.'],
['2', '1', '.', '.', '.', '.', '.'],
['2', '1', '1', '.', '.', '.', '.'],
['2', '2', '2', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [4, 2])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 3)
expect(@obj.send(:left_diagonal_win?)).to eq(true)
end
it 'should return false with left diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['2', '.', '.', '.', '.', '.', '.'],
['1', '1', '.', '.', '.', '.', '.'],
['2', '1', '1', '.', '.', '.', '.'],
['2', '2', '2', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [3, 1])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 2)
expect(@obj.send(:left_diagonal_win?)).to eq(false)
end
it 'should return false with left diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['2', '.', '.', '.', '.', '.', '.'],
['1', '1', '.', '.', '.', '.', '.'],
['2', '1', '1', '.', '.', '.', '.'],
['2', '2', '2', '1', '1', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [4, 2])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 3)
expect(@obj.send(:left_diagonal_win?)).to eq(false)
end
end
context 'right_diagonal_win? checking' do
it 'should return false with check right diagonal win due to minimal input' do
@obj.instance_variable_set(:@total_moves, 10)
expect(@obj.send(:right_diagonal_win?)).to eq(false)
end
it 'should return true with right diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '1', '2', '.', '.'],
['.', '2', '1', '1', '1', '.', '.'],
['.', '1', '2', '2', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [2, 4])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 5)
expect(@obj.send(:right_diagonal_win?)).to eq(true)
end
it 'should return true with right diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '1', '2', '.', '.'],
['.', '2', '1', '1', '1', '.', '.'],
['.', '1', '2', '2', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [4, 2])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 3)
expect(@obj.send(:right_diagonal_win?)).to eq(true)
end
it 'should return false with right diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '1', '.', '.'],
['.', '.', '.', '1', '1', '.', '.'],
['.', '2', '1', '1', '2', '.', '.'],
['.', '2', '1', '2', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [4, 2])
obj = ConnectFour::Board.new
obj.instance_variable_set(:@total_moves, 11)
obj.instance_variable_set(:@board_grid, grid)
obj.instance_variable_set(:@current_player, player)
obj.instance_variable_set(:@move, 3)
expect(obj.send(:right_diagonal_win?)).to eq(false)
end
it 'should return false with right diagonal win check' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '2', '.', '.'],
['.', '.', '.', '1', '1', '.', '.'],
['.', '2', '1', '1', '2', '.', '.'],
['.', '1', '1', '2', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [3, 3])
@obj.instance_variable_set(:@total_moves, 11)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 4)
expect(@obj.send(:right_diagonal_win?)).to eq(false)
end
it 'should return false with right diagonal win check' do
grid = [
['.', '.', '.', '2', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.'],
['.', '.', '.', '2', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.'],
['.', '.', '1', '2', '.', '.', '.'],
['2', '1', '1', '1', '2', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1, [4, 2])
obj = ConnectFour::Board.new
obj.instance_variable_set(:@total_moves, 11)
obj.instance_variable_set(:@board_grid, grid)
obj.instance_variable_set(:@current_player, player)
obj.instance_variable_set(:@move, 3)
expect(obj.send(:right_diagonal_win?)).to eq(false)
end
end
context 'full? checking' do
it 'should return true with board full check' do
grid = [
['2', '2', '1', '2', '2', '1', '2'],
['2', '2', '2', '1', '1', '1', '1'],
['1', '1', '1', '2', '2', '1', '2'],
['1', '2', '1', '1', '2', '2', '1'],
['1', '2', '1', '1', '1', '1', '2'],
['2', '1', '2', '1', '2', '2', '1']
]
player = ConnectFour::Player.new('Alice', 1, [0, 5])
@obj.instance_variable_set(:@total_moves, 42)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 5)
expect(@obj.send(:full?)).to eq(true)
end
end
context 'update' do
it 'should true with updated board' do
grid = [
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1)
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 4)
expect(@obj.send(:update)).to eq(true)
end
it 'should false with the error message' do
grid = [
['.', '.', '.', '2', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.'],
['.', '.', '.', '2', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.'],
['.', '.', '.', '2', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '.']
]
player = ConnectFour::Player.new('Alice', 1)
@obj.instance_variable_set(:@total_moves, 7)
@obj.instance_variable_set(:@board_grid, grid)
@obj.instance_variable_set(:@current_player, player)
@obj.instance_variable_set(:@move, 4)
expect(@obj.send(:update)).to eq(false)
end
end
end
| true |
d855efc9db2cd1b7305c257e5c29d294cf013e4c | Ruby | Terren45/programming-univbasics-4-crud-lab-online-web-prework | /lib/array_crud.rb | UTF-8 | 890 | 3.453125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def create_an_empty_array
[]
end
def create_an_array
["cars", "truck", "planes", "trains"]
end
def add_element_to_end_of_array = ["cars", "truck", "planes", "trains"]
add_element_to_end_of_array << "boat"
end
def add_element_to_start_of_array = ["cars", "truck", "planes", "trains"]
add_element_to_start_of_array.unshift("boat")
end
def remove_element_from_end_of_array(array) = ["cars", "truck", "planes", "trains"]
trains_array = remove_element_from_end_of_array.pop
end
def remove_element_from_start_of_array(array) = ["cars", "truck", "planes", "trains"]
cars_array = remove_element_from_start_of_array.shift
end
def retrieve_element_from_index(array, index_number)
array[1]
end
def retrieve_first_element_from_array(array)
array[0]
end
def retrieve_last_element_from_array(array)
array[3]
end
def update_element_from_index(array, index_number, element)
end
| true |
d1cc6388db33273bdc7c87d95bb06445713aa19c | Ruby | QPC-WORLDWIDE/rubinius | /spec/ruby/language/versions/for_1.8.rb | UTF-8 | 203 | 2.703125 | 3 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | describe "The for expression" do
it "repeats the loop from the beginning with 'retry'" do
j = 0
for i in 1..5
j += i
retry if i == 3 && j < 7
end
j.should == 21
end
end
| true |
d27c762e07bfbc954f3ac2ad8a8b0449d4043194 | Ruby | jwshinx/SubscriptionCircus | /lib/invoice.rb | UTF-8 | 594 | 2.625 | 3 | [] | no_license | require 'general_methods'
class Invoice
include GeneralMethods
include GeneralMethods::AddedInstanceMethods
attr_reader :customer, :date, :amount_due, :amount_paid
def initialize options={}
@customer = options[:customer] ? options[:customer] : 'N/A'
@date = options[:date] ? options[:date] : 'N/A'
@amount_paid = options[:amount_paid] ? options[:amount_paid] : 'N/A'
@amount_due = options[:amount_due] ? options[:amount_due] : 'N/A'
end
def to_s
%Q{
customer: #{@customer.name}
date: #{@date}
amount due: #{@amount_due}
amount paid: #{@amount_paid}
}
end
end
| true |
d15fc749e4261db2197a0501b44cbf3e4c7cbbff | Ruby | javogel/IH_Coursework | /Week_2/Day_2/OnlineCalculator/lib/Calculator.rb | UTF-8 | 853 | 3.640625 | 4 | [] | no_license | class Calculator
def initialize
end
def self.calculate(num1, num2, operation)
case operation
when "add"
self.add(num1, num2)
when "subtract"
self.subtract(num1, num2)
when "multiply"
self.multiply(num1, num2)
when "divide"
self.divide(num1, num2)
end
end
def self.add(num1, num2)
num1 + num2
end
def self.subtract(num1, num2)
num1 - num2
end
def self.multiply(num1, num2)
num1 * num2
end
def self.divide(num1, num2)
num1 / num2
end
def self.load
lines = []
File.readlines(@filename).each do |line|
lines << line
end
return lines[0]
end
def self.save(result)
@filename = "persitance.txt"
@result = result.to_s
open(@filename, 'w') do |f|
f << @result + "\n"
end
end
end
calc = Calculator.save("25")
| true |
263bedc2eb65e6b88d5139df2c3422aec9016b66 | Ruby | oliverbebber/key-for-min-value-onl01-seng-pt-081720 | /key_for_min.rb | UTF-8 | 2,046 | 4.03125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
# def method(hash)
# iterate over the hash
# returns key with smallest value
# if method is called and has an empty hash => nil
require 'pry'
# return nil - passes, fails returning smallest hash value
def key_for_min_value(name_hash)
return nil if name_hash == {}
end
# find smallest key value
# iterate thru all key value pairs
# keep record of smallest key
# create variable for lowest key
# lowest_key == default value
# create loop
# .each |key, value|
# if value is < new_key
# def new lowest key variable
# create two variables to store keys and values in, one at a time...iterate over hash and compare each one to the last
# def key_for_min_value(name_hash)
# min val = <-- figure out a value for this variable
# min key = <-- figure out a starting value for this variable
#
# name_hash.collect/each do |key, value|
# if value < min_val
# set min_val = value in hash
#end
#end
# set min_val = nil
# if min_val = nil
# min_val = value
# end
# if value < min_val
# min_val = value
# end
# fails every test...
# def key_for_min_value(name_hash)
# smallest_val = nil
# smallest_key = nil
# name_hash.each do |value|
# if smallest_val < value
# smallest_val = value
# end
# name_hash.each do |key|
# if smallest_key < key
# smallest_key = key
# end
# end
# end
# end
# fails every test
# def key_for_min_value(name_hash)
# smallest_val = nil
# smallest_key = nil
# name_hash.each do |key, value|
# if smallest_val <= value
# smallest_val == value
# elsif smallest_key <= key
# smallest_key == key
# end
# end
# end
#fails every test
def key_for_min_value(name_hash) # <-- argument for method
low = nil
result = nil
name_hash.each do |key, value| # <-- parameters for iteration
if low == nil || value < low
low = value
result = key
end
end
result
end
# end
# result = key
# end
| true |
29cbc369ca6ed3659126d332374a7b34e5d00f25 | Ruby | timoh/craftbeer | /app/models/geocoder.rb | UTF-8 | 3,021 | 3.0625 | 3 | [] | no_license | class Geocoder
require 'rest_client'
require 'uri'
# requires Rails.application.secrets.googlemaps_token
# API docs: https://developers.google.com/maps/documentation/geocoding
def Geocoder.get_token
access_token = ENV['GOOGLEMAPS_TOKEN'] || Rails.application.secrets.googlemaps_token
begin
raise "Google Maps token missing from secrets.yml / ENV variables!" unless access_token
return access_token
rescue
puts "Getting token failed!"
end
end
def Geocoder.get_city(response)
response['results'][0]['address_components'].each do |adr_comp|
if adr_comp['types'][0].include? "administrative_area"
return adr_comp['long_name']
end
end
return ''
end
def Geocoder.geocoder_works? # returns true if geocoder works, otherwise raises an error
begin
token = Geocoder.get_token
rescue
puts "Cannot get token!"
else
res = Geocoder.reverse_geocode(60.1616054,24.8814315)
should_be = "Taivaanvuohentie 8, 00200 Helsinki, Finland"
if res == should_be
return true
else
raise "Result not as expected: #{res}"
end
end
end
def Geocoder.geocode(address, country="FI") # returns Hash = {:lat, :lng}
begin
access_token = Geocoder.get_token
escaped_address = URI.escape(address)
rescue
puts "Initialization failed!"
else
output = RestClient.get "https://maps.googleapis.com/maps/api/geocode/json?address=#{escaped_address}&key=#{access_token}&components=country:#{country}"
output = JSON.parse(output)
begin
# returns {:lat, :lng}
AddressQuery.create(query: address, city: Geocoder.get_city(output), result_address: output['results'][0]['formatted_address'], raw_result: output, coords: output['results'][0]['geometry']['location'])
return output['results'][0]['geometry']['location']
rescue
puts "Geocoding failed!"
end
end
end
def Geocoder.reverse_geocode(lat, lng) # returns String (formatted_address)
begin
access_token = Geocoder.get_token
escaped_lat = URI.escape(lat.to_s)
escaped_lng = URI.escape(lng.to_s)
rescue
puts "Initialization failed!"
else
url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=#{escaped_lat},#{escaped_lng}&key=#{access_token}&result_type=street_address"
output = RestClient.get url
output = JSON.parse(output)
begin
address = output['results'][0]['formatted_address']
rescue
puts "No results!"
puts output
puts "Query was:"
puts url
else
begin
# returns {:lat, :lng}
AddressQuery.create(query: address, city: Geocoder.get_city(output), result_address: output['results'][0]['formatted_address'], raw_result: output, coords: output['results'][0]['geometry']['location'])
return address
rescue
puts "Geocoding failed!"
end
end
end
end
end
| true |
7e5f2d22dda84c98e2f2484ffb2995b83bb8c87a | Ruby | acasasayas/IronHack_exercises | /PreWork/FizzBuzz2.rb | UTF-8 | 571 | 3.34375 | 3 | [] | no_license | number = 1
output = "nothing"
while number <= 100
if number % 3 == 0
output = "Fizz!"
end
if number % 5 == 0
output = "Buzz!"
end
if number % 3 == 0 && number % 5 == 0
output = "Fizz!Buzz!"
end
if output == "nothing" && number / 10 != 1
output = "#{number}"
end
if number /10 == 1 && output == "nothing"
output = "Bang!"
elsif number / 10 == 1 && output != "Bang!"
output = "Bang!" + output
elsif number / 100 ==1
output = "Bang!" + output
elsif number == 1
output = "Bang!"
end
number = number + 1
puts output
output = "nothing"
end | true |
08674b9ccb9a2bfae4a18288ac9e02a50700c919 | Ruby | teacplusplus/sait-znakomstv | /config/initializers/lang_correct.rb | UTF-8 | 2,086 | 3.359375 | 3 | [] | no_license | #encoding: UTF-8
class LangCorrect
REPLACES = {
#CASE_UPPER #case_lower
"Ё" => '~', "а" => '`', #Ё ё
"А" => 'F', "а" => 'f', #А а
"Б" => '<', "б" => ',', #Б б
"В" => 'D', "в" => 'd', #В в
"Г" => 'U', "г" => 'u', #Г г
"Д" => 'L', "д" => 'l', #Д д
"Е" => 'T', "е" => 't', #Е е
"Ж" => ':', "ж" => ';', #Ж ж
"З" => 'P', "з" => 'p', #З з
"И" => 'B', "и" => 'b', #И и
"Й" => 'Q', "й" => 'q', #Й й
"К" => 'R', "к" => 'r', #К к
"Л" => 'K', "л" => 'k', #Л л
"М" => 'V', "м" => 'v', #М м
"Н" => 'Y', "н" => 'y', #Н н
"О" => 'J', "о" => 'j', #О о
"П" => 'G', "п" => 'g', #П п
#CASE_UPPER #case_lower
"Р" => 'H', "р" => 'h', #Р р
"С" => 'C', "с" => 'c', #С с
"Т" => 'N', "т" => 'n', #Т т
"У" => 'E', "у" => 'e', #У у
"Ф" => 'A', "ф" => 'a', #Ф ф
"Х" => '{', "х" => '[', #Х х
"Ц" => 'W', "ц" => 'w', #Ц ц
"Ч" => 'X', "ч" => 'x', #Ч ч
"Ш" => 'I', "ш" => 'i', #Ш ш
"Щ" => 'O', "щ" => 'o', #Щ щ
"Ь" => '}', "ъ" => ']', #Ъ ъ
"Ы" => 'S', "ы" => 's', #Ы ы
"ь" => 'M', "ь" => 'm', #Ь ь
"Э" => '"', "э" => "'", #Э э
"Ю" => '>', "ю" => '.', #Ю ю
"Я" => 'Z', "я" => 'z', #Я я
}
INVERT_REPLACES = REPLACES.invert
def self.make(str)
result = ''
str.to_s.each_char do |char|
if INVERT_REPLACES.has_key?(char)
result << INVERT_REPLACES[char]
else
result << char
end
end
return result
end
def self.unmake(str)
result = ''
str.to_s.each_char do |char|
if REPLACES.has_key?(char)
result << REPLACES[char]
else
result << char
end
end
return result
end
end | true |
b32e675dc3f43b8fd324f8e0b6c2c640d635f872 | Ruby | MachineShop-IOT/machineshop_gem | /machineshop/lib/machineshop/api_resource.rb | UTF-8 | 946 | 2.625 | 3 | [
"MIT"
] | permissive | module MachineShop
class APIResource < MachineShopObject
def self.class_name
self.name.split('::')[-1]
end
def self.url()
if self == APIResource
raise NotImplementedError.new('APIResource is an abstract class. You should perform actions on its subclasses (Device, Rule, etc.)')
end
ret = "/platform/#{CGI.escape(class_name.underscore)}"
ret
end
def url
unless id = self['id']
raise InvalidRequestError.new("Could not determine which URL to request: #{self.class} instance has invalid ID: #{id.inspect}", 'id')
end
ret = "#{self.class.url}/#{CGI.escape(id)}"
ret
end
def refresh
response = MachineShop.get(url, @auth_token)
refresh_from(response, auth_token)
self
end
def self.retrieve(id, auth_token=nil)
instance = self.new(id, auth_token)
instance.refresh
instance
end
end
end
| true |
313ca1fa57c773bb88bfb672504aa1ff975518e0 | Ruby | claritasf/Ruby_Web_Server_and_Browser | /simple_server.rb | UTF-8 | 1,125 | 3.03125 | 3 | [] | no_license | require 'socket'
require 'json' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
puts "Listening on port 2000"
loop { # Servers run forever
client = server.accept # Wait for a client to connect
request = client.gets.split(" ")
request_method = request[0]
request_path = request[1]
case request_method
when "GET"
path = request_path
body = ""
if File.exist?(path)
body = File.read(path)
status_code = 200
reason_phrase = "OK"
else
status_code = 404
phrase = "Not Found"
end
client.puts "HTTP/1.0 #{status_code} #{phrase}"
client.puts(Time.now.ctime)
client.puts "Content-Length: #{body.size}"
client.puts
client.puts "#{body}"
when "POST"
body = request.last
params = JSON.parse(body)
file_template = File.read("thanks.html")
page_content = "<li>Name: #{params["viking"]["name"]}</li><li>Email: #{params["viking"]["email"]}</li>"
thanks_page = file_template.gsub("<%= yield %>", page_content)
client.puts thanks_page
end
client.close
}
| true |
6104b102abaf919be8719e8ed4fdfc53825f17ef | Ruby | salbonico/activerecord-tvshow-v-000 | /app/models/show.rb | UTF-8 | 452 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Show < ActiveRecord::Base
def self.highest_rating
Show.maximum(:rating)
end
def self.most_popular_show
Show.find_by(rating:Show.highest_rating)
end
def self.lowest_rating
Show.minimum(:rating)
end
def self.least_popular_show
Show.find_by(rating:Show.lowest_rating)
end
def self.ratings_sum
Show.sum(:rating)
end
def self.popular_shows
Show.where("rating > ?",5)
end
def self.shows_by_alphabetical_order
Show.all.order(:name)
end
end
| true |
f9c3d162b15e8d9938c464ffdd60aab47f707d48 | Ruby | mogox/mission-to-mars | /app/rover.rb | UTF-8 | 966 | 3.625 | 4 | [] | no_license | class Rover
attr_accessor :instructions, :direction, :x, :y
def initialize(position, instructions = nil)
attributes = position.split
@x = attributes[0].to_i
@y = attributes[1].to_i
@direction = RoverDirection.new attributes[2]
self.instructions = instructions
end
def follow_instructions
instructions.split('').each do |command|
execute command
end
end
def change_direction(rotation)
if rotation == 'L'
@direction.value -= 1
else
@direction.value += 1
end
@direction.value = @direction.value % 4
end
private
def execute(command)
if command == "M"
move_forward
else
change_direction command
end
end
def move_forward
moving_direction = direction.value
if moving_direction == 0
@y += 1
elsif moving_direction == 1
@x += 1
elsif moving_direction == 2
@y -= 1
elsif moving_direction == 3
@x -= 1
end
end
end
| true |
879eae94e5f57ecc9bd0fea00a0af1d03497be6a | Ruby | bvluong/Chess | /inheritance_practice/employee.rb | UTF-8 | 1,291 | 3.796875 | 4 | [] | no_license | class Employee
attr_accessor :salary
def initialize name, title, salary, boss
@name = name
@title = title
@salary = salary
@boss = boss
@multiplier = 1
end
def bonus multiplier
@salary * multiplier
end
end
class Manager < Employee
attr_accessor :underlings
def initialize name, title, salary, boss
super name, title, salary, boss
@underlings = []
end
# def initialize name, title, salary, boss, underlings
# super name, title, salary, boss
# @underlings = underlings
# end
def bonus multiplier
employee_salary = @underlings.reduce(0){|sum, employee|
sum + employee.salary + (employee.class == Manager ? employee.sum_of_underlings : 0)
}
employee_salary * multiplier
end
def sum_of_underlings
@underlings.reduce(0){|sum, employee| sum + employee.salary}
end
end
# manager = Manager.new("Bob", "Software Engineer")
ned = Manager.new("Ned", "Founder", 1_000_000, nil)
darren = Manager.new("Darren", "TA Manager", 78000, ned)
ned.underlings << darren
shawn = Employee.new("Shawn", "TA", 12000, darren)
david = Employee.new("David", "TA", 10000, darren)
darren.underlings << shawn
darren.underlings << david
p ned.bonus(5) # => 500_000
p darren.bonus(4) # => 88_000
p david.bonus(3) # => 30_000
| true |
769a7e2b7a242a0ebd26db736cd64fefff30e0b8 | Ruby | roosterchicken/beemovie-rb | /lib/beemovie/word.rb | UTF-8 | 446 | 2.96875 | 3 | [
"MIT"
] | permissive | module Beemovie
class Word
def self.multiplySentences(num, array)
string = ""
globalnum = num
while globalnum > 0
if num == 1
string = array.sample
else
string = string + array.sample + " "
end
globalnum = globalnum - 1
end
return string.lstrip
end
end
end | true |
a3428dd5ecfeed66c514f8e0ec24568d7129e94f | Ruby | thegeekbrandon/rubyScripts | /Ruby-Scripts/input.rb | UTF-8 | 103 | 3.59375 | 4 | [] | no_license | puts "Enter your name:"
name = gets.chomp
greeting = "Hello, #{name}. You are awesome!"
puts greeting
| true |
617f8d686575004938a562e1560eea436591184c | Ruby | luismedinacoca/LearnToCodeWithRuby | /Section14/Lecture174-YieldingWithArguments04.rb | UTF-8 | 305 | 3.875 | 4 | [] | no_license | def number_evaluation(num1, num2, num3)
puts "Inside the method"
yield(num1, num2, num3)
#puts "Back inside the method!"
end
sum = number_evaluation(5, 15, 10){ |num1, num2, num3| num1 + num2 + num3 }
product = number_evaluation(5, 15, 10){ |num1, num2, num3| num1 * num2 * num3 }
p sum
p product
| true |
1848f33ad368d51c648a2960f574310f99cfcd91 | Ruby | umar006/social-media-api | /app/controllers/hashtags_controller.rb | UTF-8 | 444 | 2.53125 | 3 | [] | no_license | require './app/models/hashtag'
class HashtagsController
def create(hashtag)
new_hashtag = Hashtag.new(hashtag)
new_hashtag.save
end
def update(hashtag)
update_hashtag = Hashtag.new(hashtag)
update_hashtag.update
end
def self.find_by_hashtag(hashtag)
Hashtag.find_by_hashtag(hashtag).first
end
def self.top_5_past_24h
Hashtag.find_top_5_past_24h
end
def self.find_all
Hashtag.find_all
end
end | true |
b79be5877b4a9b3c52b162829784b5f4e2393a31 | Ruby | tkgs0109/DIC_scripting_task | /app/models/task.rb | UTF-8 | 1,416 | 2.65625 | 3 | [] | no_license | class Task < ApplicationRecord
default_scope -> { order("tasks.id") }
belongs_to :user
has_many :parent_relationals, class_name: 'Relational', foreign_key: :parent_id
has_many :children_relationals, class_name: 'Relational', foreign_key: :children_id, dependent: :destroy
has_many :parent_task, through: :children_relationals, source: :parent
has_many :children_tasks, through: :parent_relationals, source: :children, dependent: :destroy
validates :title, presence: true
def self.descendant_tasks(uid)
descendant_ids = Array.new
mytasks = Task.where(user_id: uid)
mytasks.each do |task|
unless task.children_tasks.any?
descendant_ids << task.id
end
end
return descendant_ids
end
# 自分も含めた親子関係を配列で返すメソッド
def clans_to_me
clan = Array.new
task = self
clan.unshift(task.id)
while true
if task.parent_task.first.nil?
break
else
clan.unshift(task.parent_task.ids.first)
task = Task.find(clan.first)
end
end
return clan
end
# 自分の親までの親子関係を配列で返すメソッド
def clans
clan = Array.new
task = self
while true
if task.parent_task.first.nil?
break
else
clan.unshift(task.parent_task.ids.first)
task = Task.find(clan.first)
end
end
return clan
end
end
| true |
1a312b9cbc1d3cb2166d672b93e5ac7dde7284e5 | Ruby | il-tmfv/sq-test-task | /app/models/transaction.rb | UTF-8 | 1,929 | 2.8125 | 3 | [
"MIT"
] | permissive | class Transaction < ActiveRecord::Base
validate :seller_and_buyer_exist, :buyer_meets_required_level,
:buyer_have_enough_space, :buyer_have_enough_money
before_validation :get_info_for_validation
after_create :change_data_after_create
private
def get_info_for_validation
@seller = Player.find(seller_id)
@buyer = Player.find(buyer_id)
@offer = Offer.find(offer_id)
end
def change_data_after_create
@buyer.reload
@seller.reload
@offer.reload
@buyer.balance -= @offer.price
@seller.balance += @offer.price
begin
ActiveRecord::Base.transaction do
storage_product = StorageProduct.find_by(storage_id: @buyer.storage.id, product_id: @offer.product.id)
if storage_product.blank?
StorageProduct.create!(
storage_id: @buyer.storage.id,
product_id: @offer.product.id,
quantity: @offer.quantity
)
else
storage_product.quantity += @offer.quantity
storage_product.save
end
@buyer.save
@seller.save
@offer.delete
end
rescue ActiveRecord::StatementInvalid
self.delete
end
end
def seller_and_buyer_exist
if @seller.blank?
errors.add(:seller_id, 'Seller should exist')
end
if @buyer.blank?
errors.add(:buyer_id, 'Buyer should exits')
end
end
def buyer_meets_required_level
if @buyer.level < @offer.product.required_level
errors.add(:buyer_id, "Buyer's level should be greater or equal to required level of product")
end
end
def buyer_have_enough_space
if @buyer.storage.free_space < @offer.quantity
errors.add(:buyer_id, 'Buyer do not have enough free space at his storage')
end
end
def buyer_have_enough_money
if @buyer.balance < @offer.price
errors.add(:buyer_id, 'Buyer do not have enough money')
end
end
end
| true |
f31741ec5b255ab1195b78fe767224a92318a905 | Ruby | muniere/tailor | /bin/tailor | UTF-8 | 2,442 | 2.625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'thor'
require 'ostruct'
require 'colorize'
require 'awesome_print'
require_relative '../lib/tailor'
class CLI < Thor
#
# start
#
desc 'start <project>', 'start to tail logs'
def start(name='default')
# load
project = Tailor::Project.load(name).validate
# message(main)
queue = Queue.new
Thread.start do
while message = queue.pop
if message.is_a?(Exception)
STDERR.puts(message.inspect.red)
elsif message.is_a?(String)
STDOUT.puts(message)
else
STDOUT.puts(message.inspect)
end
end
end
# tail
clients = project.servers.map{ |server|
Tailor::Client.new(path: project.path, server: server, queue: queue)
}
begin
Parallel.each(clients, in_threads: clients.length) do |client|
client.start
end
rescue => e
STDERR.puts(e.inspect.red)
end
rescue Interrupt
# do nothing
end
desc 'exec <project>', 'alias of :start'
def exec(*args)
self.invoke(:start, *args)
end
#
# create
#
desc 'create <project>', 'create a new project'
def create(name)
Tailor::Project.create(name)
Tailor::Project.edit(name)
end
desc 'new <project>', 'alias of :create'
def new(*args)
self.invoke(:create, *args)
end
#
# edit
#
desc 'edit <project>', 'edit a project'
def edit(name)
Tailor::Project.edit(name)
end
#
# delete
#
desc 'delete <project>', 'delete a project'
def delete(name)
Tailor::Project.delete(name)
end
desc 'rm <project>', 'alias of :delete'
def rm(*args)
self.invoke(:delete, *args)
end
#
# list
#
desc 'list', 'list projects'
def list
puts Tailor::Project.list
end
desc 'ls', 'alias of :list'
def ls
self.invoke(:list)
end
#
# completion
#
desc 'complete', 'list completions'
option :bash, :type => :boolean, :default => false
option :zsh , :type => :boolean, :default => false
def complete(*args)
opts = OpenStruct.new(options)
if args.empty?
self.class.commands.each do |name, cmd|
next if name == 'complete'
if opts.zsh
puts "#{name}:#{cmd.description}"
else
puts "#{name}"
end
end
return
end
if ['start', 'exec', 'edit', 'delete', 'rm'].include?(args.first)
puts Project.list
end
end
end
CLI.start
| true |
eab51bb8879363ce0d3e1ea152ce18f7577815f4 | Ruby | fanjieqi/LeetCodeRuby | /701-800/795. Number of Subarrays with Bounded Maximum.rb | UTF-8 | 355 | 3.125 | 3 | [
"MIT"
] | permissive | # @param {Integer[]} a
# @param {Integer} l
# @param {Integer} r
# @return {Integer}
def num_subarray_bounded_max(a, l, r)
res, dp, prev = 0, 0, -1
a.each_with_index do |num, i|
res += dp if num < l && i > 0
if num > r
dp = 0
prev = i
end
if l <= num && num <= r
dp = i - prev
res += dp
end
end
res
end
| true |
61a4b9de3cd78a9b6bc929828944836972df26f7 | Ruby | eeuresti/username_generator | /username.rb | UTF-8 | 1,419 | 3.125 | 3 | [] | no_license | # Make sure to run the tests in your /spec folder
# Run `rspec /spec/username_spec.rb` to get started.
def format_name(first, last)
if first == "" || last == ""
return nil
end
new_first = first.gsub(/\W+/,"")
new_last = last.gsub(/\W+/,"")
username = new_first[0] + new_last
username = username.downcase.gsub(/\d/,"")
end
def format_year(my_year)
my_year = my_year.to_s
if my_year.length != 4
return nil
end
my_year = my_year.split(//, 3)
my_year = my_year[2]
end
def build_username(first, last, year, user_type=0)
type_array = ["", "seller-", "manager-", "admin-"]
username = format_name(first, last)
username = username + format_year(year)
return username = type_array[user_type] + username
end
$usernames = {}
def generate_username(first_name, last_name, birth_year, privilege_level=0)
new_username = build_username(first_name, last_name, birth_year, privilege_level)
if $usernames[new_username] == nil
$usernames[new_username] = 0
return new_username
else
$usernames[new_username] += 1
new_username = new_username + "_" + $usernames[new_username].to_s
return new_username
end
# usernames.index(new_username)
# if usernames.index(new_username) == nil
# usernames.push(new_username)
# return new_username
# else
# new_username = new_username + "_1"
# usernames.push(new_username)
# return new_username
# end
end
| true |
c7b5c9cabdcdcf0d98ff6e03898233ee96110075 | Ruby | ostdotcom/SimpleTokenApi | /lib/global_constant/country_nationality.rb | UTF-8 | 13,951 | 2.5625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module GlobalConstant
class CountryNationality
require 'csv'
# GlobalConstant::CountryNationality
# Get Aml Country From Ip
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Array]
#
def self.get_aml_country_from_ip(ip_address)
geoip_country = get_maxmind_country_from_ip(ip_address)
return [] if geoip_country.blank?
blacklisted_country = maxmind_to_aml_country_hash[geoip_country.upcase]
blacklisted_country.present? ? blacklisted_country : []
end
# Get Maxmind Country From Ip
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [String]
#
def self.get_maxmind_country_from_ip(ip_address)
geo_ip_obj = Util::GeoIpUtil.new(ip_address: ip_address)
geoip_country = geo_ip_obj.get_country_name.to_s rescue ''
geoip_country.to_s.upcase
end
# # List of states disallowed to participate in ICO
# #
# # * Author: Tejas
# # * Date: 01/08/2018
# # * Reviewed By: Aman
# #
# # @return [Hash]
# #
# def self.disallowed_states
# {
# 'united states of america' => {
# 'newyork' => 'NY',
# 'new york' => 'NY',
# 'new york state' => 'NY',
# 'newyorkstate' => 'NY',
# 'new yorkstate' => 'NY',
# 'ny' => 'NY',
# 'nyc' => 'NY'
# },
# 'ukraine' => {
# 'crimea' => 'Crimea'
# },
# 'russia' => {
# 'crimea' => 'Crimea'
# }
# }
# end
# list of aml countries
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Array]
#
def self.countries
@countries ||= aml_country_to_maxmind_hash.keys
end
# Get country name from its MD5 hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [String]
#
def self.country_name_for(md5_country)
country_md5_map[md5_country] || ''
end
# List of aml nationalities
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Array]
#
def self.nationalities
@nationalities ||= nationality_iso_map.keys
end
# Get nationality name from its MD5 hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [String]
#
def self.nationality_name_for(md5_nationality)
nationality_md5_map[md5_nationality] || ''
end
private
# Generate MD5 to aml country name hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.country_md5_map
@country_md5_map ||= generate_md5_map_for(countries + deleted_countries)
end
# Generate MD5 to aml nationality name hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.nationality_md5_map
@nationality_md5_map ||= generate_md5_map_for(nationalities + deleted_nationalities)
end
# Generate the MD5 map of an array of string
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.generate_md5_map_for(arr_list)
md5_map = {}
arr_list.each do |value|
md5_value = Md5UserExtendedDetail.use_any_instance.get_hashed_value(value)
md5_map[md5_value] = value
end
md5_map
end
# Aml country name to Maxmind country hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash] one aml country can have multiple maxmind country name
#
def self.aml_country_to_maxmind_hash
@aml_country_to_maxmind_hash ||= begin
country_mapping = {}
aml_country_to_maxmind_data.each do |row|
key = row[0].upcase
value = row.drop(1)
country_mapping[key] = value
end
country_mapping
end
end
# Maxmind country name to Aml country hash
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.maxmind_to_aml_country_hash
@maxmind_to_aml_country_hash ||= begin
inverse_hash = {}
aml_country_to_maxmind_hash.each do |aml_country, maxmind_countries|
maxmind_countries.each do |maxmind_country|
key = maxmind_country.upcase
inverse_hash[key] ||= []
inverse_hash[key] << aml_country
end
end
inverse_hash
end
end
# Perform
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.aml_country_to_maxmind_data
@aml_country_to_maxmind_data ||= CSV.read("#{Rails.root}/config/aml_country_to_maxmind_mapping.csv")
end
# list of cynopsis nationalities removed from previous list of cynopsis nationalities
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Array] # these nationalities were deleted from our list of cynopsis nationalities on 02/11/2018
#
def self.deleted_nationalities
[
"ASCENSION",
"TRISTAN DA CUNHA",
"BRITISH INDIAN OCEAN TERRITORY",
"AUSTRALIAN ANTARCTIC TERRITORY",
"BAKER ISLAND",
"BRITISH ANTARCTIC TERRITORY",
"BRITISH SOVEREIGN BASE AREAS",
"JARVIS ISLAND",
"FRENCH SOUTHERN AND ANTARCTIC LANDS",
"CLIPPERTON ISLAND",
"ROSS DEPENDENCY",
"QUEEN MAUD LAND",
"PETER I ISLAND"
]
end
# list of aml countries removed from previous list of aml countries
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Array] # these countries were deleted from our list of aml country on 01/08/2018
#
def self.deleted_countries
[
# countries which were removed from cynopsis list previously
"BRITISH INDIAN OCEAN TERRITORY",
"ASHMORE AND CARTIER ISLANDS",
"AUSTRALIAN ANTARCTIC TERRITORY",
"BAKER ISLAND",
"BRITISH ANTARCTIC TERRITORY",
"BRITISH SOVEREIGN BASE AREAS",
"JARVIS ISLAND",
"FRENCH SOUTHERN AND ANTARCTIC LANDS",
"CLIPPERTON ISLAND",
"ROSS DEPENDENCY",
"QUEEN MAUD LAND",
"PETER I ISLAND",
# countries not in acuris list
"ANTARCTICA",
"FRENCH SOUTHERN TERRITORIES",
"HOWLAND ISLAND",
"KINGMAN REEF",
"NAGORNO-KARABAKH",
"PRIDNESTROVIE (TRANSNISTRIA)",
"SOUTH OSSETIA",
"UNITED STATES MINOR OUTLYING ISLANDS"
]
end
# Usa States with space regex to handle multiple or 0 spaces
#
# * Author: Tejas
# * Date: 02/07/2018
# * Reviewed By:
#
# @return [String]
#
def self.regex_usa_states
@regex_usa_states ||= begin
arr = []
usa_states.each do |state|
arr << Util::CommonValidateAndSanitize.get_words_regex_for_multi_space_support(state)
end
arr
end
end
# canada States with space regex to handle multiple or 0 spaces
#
# * Author: Tejas
# * Date: 02/07/2018
# * Reviewed By:
#
# @return [String]
#
def self.regex_canada_states
@regex_canada_states ||= begin
arr = []
canada_states.each do |state|
arr << Util::CommonValidateAndSanitize.get_words_regex_for_multi_space_support(state)
end
arr
end
end
# Usa States
#
# * Author: Tejas
# * Date: 02/07/2018
# * Reviewed By:
#
# @return [Array]
#
def self.usa_states
['USA', 'United States Minor Outlying Islands', 'United States of America',
'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida',
'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland',
'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'Dakota', 'Ohio', 'Oklahoma', 'Oregon',
'Carolina', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia',
'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', 'CAROLINA', 'Pennsylvania', 'Rhode Island']
end
# Canada States
#
# * Author: Tejas
# * Date: 10/07/2018
# * Reviewed By:
#
# @return [Array]
#
def self.canada_states
['Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador ',
'Nova Scotia', 'Ontario', 'Prince Edward Island', 'Quebec', 'Saskatchewan', 'Northwest Territories',
'Nunavut', 'Yukon']
end
# Nationality Country Map
#
# * Author: Tejas
# * Date: 09/07/2018
# * Reviewed By:
#
# @return [Hash]
#
def self.nationality_country_map
generate_nationality_country_map
end
# Nationality Iso Map
#
# * Author: Tejas
# * Date: 09/07/2018
# * Reviewed By:
#
# @return [Hash]
#
def self.nationality_iso_map
generate_nationality_iso_map
end
# Generate Nationality Country Map
#
# * Author: Tejas
# * Date: 09/07/2018
# * Reviewed By:
#
# @return [Hash] nationality_country_mapping
#
def self.generate_nationality_country_map
@nationality_country_mapping ||= {}
if @nationality_country_mapping.blank?
fetch_country_nationality_mapping.each do |row|
sp = row.gsub("\r", "").split(",")
key = sp[0].upcase
val = sp.drop(2)
@nationality_country_mapping[key] = val
end
end
@nationality_country_mapping
end
# Generate Nationality Iso Map
#
# * Author: Tejas
# * Date: 09/07/2018
# * Reviewed By:
#
# @return [Hash] nationality_iso_mapping
#
def self.generate_nationality_iso_map
@nationality_iso_mapping ||= {}
if @nationality_iso_mapping.blank?
fetch_country_nationality_mapping.each do |row|
sp = row.gsub("\r", "").split(",")
key = sp[0].upcase
value = sp[1].upcase
@nationality_iso_mapping[key] = value
end
end
@nationality_iso_mapping
end
# Fetch Country Nationality Mapping
#
# * Author: Tejas
# * Date: 09/07/2018
# * Reviewed By:
#
# @return Array[String] fetch_file_contents
#
def self.fetch_country_nationality_mapping
@fetch_file_contents ||= File.open("#{Rails.root}/config/nationality_and_country_mapping.csv",
"rb").read.split("\n")
end
# Updated Country Hash By Cynopsis
# renamed country hash for difference in cynopsis and acuris
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.updated_country_hash
{
"BAHAMAS" => "BAHAMAS, THE",
"BURMA (REPUBLIC OF THE UNION OF MYANMAR)" => "MYANMAR",
"CARIBBEAN NETHERLANDS" => "NETHERLANDS ANTILLES",
"CAYMAN ISLANDS" => "CAYMAN ISLANDS, THE",
"CONGO (REPUBLIC OF)" => "CONGO, REPUBLIC OF THE",
"COTE D'IVOIRE (IVORY COAST)" => "CÔTE D'IVOIRE",
"DEMOCRATIC REPUBLIC OF THE CONGO" => "CONGO, DEMOCRATIC REPUBLIC OF THE",
"GAMBIA" => "GAMBIA, THE",
"MACEDONIA" => "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF",
"MICRONESIA" => "MICRONESIA, FEDERATED STATES OF",
"NORTH KOREA" => "KOREA, NORTH",
"RUSSIAN FEDERATION" => "RUSSIA",
"SAINT MARTIN (NETHERLANDS)" => "ST. MAARTEN",
"SAINT VINCENT AND GRENADINES" => "SAINT VINCENT AND THE GRENADINES",
"SOMALILAND" => "SOMALIA",
"SOUTH KOREA" => "KOREA, SOUTH",
"TIMOR-LESTE" => "EAST TIMOR",
"VATICAN" => "VATICAN CITY",
"WALLIS AND FUTUNA ISLANDS" => "WALLIS AND FUTUNA",
"ABKHAZIA"=> 'GEORGIA',
"ALAND ISLANDS"=> 'FINLAND',
"ASCENSION"=> 'UNITED KINGDOM',
"BOUVET ISLAND"=> 'NORWAY',
"CHRISTMAS ISLAND"=> 'AUSTRALIA',
"COCOS (KEELING) ISLANDS"=> 'AUSTRALIA',
"CORAL SEA ISLANDS"=> 'AUSTRALIA',
"CURACAO"=> 'NETHERLANDS ANTILLES', # as per google
"FALKLAND ISLANDS"=> 'UNITED KINGDOM',
"HEARD AND MCDONALD ISLANDS"=> 'AUSTRALIA',
"JOHNSTON ATOLL"=> 'UNITED STATES OF AMERICA',
"MIDWAY ISLANDS"=> 'UNITED STATES OF AMERICA',
"NAVASSA ISLAND"=> 'UNITED STATES OF AMERICA',
"NORTHERN CYPRUS"=> 'CYPRUS',
"PALMYRA ATOLL"=> 'UNITED STATES OF AMERICA',
"PITCAIRN"=> 'UNITED KINGDOM',
"PITCAIRN ISLANDS"=> 'UNITED KINGDOM',
"SAINT BARTHELEMY"=> 'FRANCE',
"SAINT HELENA"=> 'UNITED KINGDOM',
"SAINT MARTIN (FRANCE)"=> 'FRANCE',
"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS"=> 'UNITED KINGDOM',
"SVALBARD AND JAN MAYEN ISLANDS"=> 'NORWAY',
"TOKELAU"=> 'NEW ZEALAND',
"TRISTAN DA CUNHA"=> 'UNITED KINGDOM',
"WAKE ISLAND" => 'UNITED STATES OF AMERICA'
}
end
# Updated Nationality Hash By Cynopsis
#
# * Author: Tejas
# * Date: 01/08/2018
# * Reviewed By: Aman
#
# @return [Hash]
#
def self.updated_nationality_hash
{
"AFGHANI" => "AFGHAN",
"BAHRAINIAN" => "BAHRAINI",
"LITHUNIAN" => "LITHUANIAN"
}
end
end
end
| true |
e322b198cad1b5ecd950aeb23be9b227a813dd1a | Ruby | enspirit/wlang | /spec/unit/compiler/test_parser.rb | UTF-8 | 2,414 | 2.625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
module WLang
describe Parser do
def parse(input)
WLang::Parser.new.call(input)
end
let(:expected) {
[:template,
[:fn,
[:strconcat,
[:static, "Hello "],
[:wlang, "$",
[:fn,
[:static, "who"]]],
[:static, "!"]]]]
}
it 'should parse "Hello ${world}!" as expected' do
parse(hello_tpl).should eq(expected)
end
it 'should support high-order wlang' do
expected = \
[:template,
[:fn,
[:wlang, "$",
[:fn,
[:wlang, "$",
[:fn,
[:static, "who"]]]]]]]
parse("${${who}}").should eq(expected)
end
it 'should support mutli-block functions' do
expected = \
[:template,
[:fn,
[:wlang, "$",
[:fn, [:static, "first" ]],
[:fn, [:static, "second"]]]]]
parse("${first}{second}").should eq(expected)
end
it 'should support wlang tags inside normal { ... }' do
expected = \
[:template,
[:fn,
[:strconcat,
[:static, "hello "],
[:strconcat,
[:static, "{"],
[:strconcat,
[:static, "bar "],
[:wlang, "$",
[:fn,
[:static, "second"]]]],
[:static, "}"]]]]]
parse("hello {bar ${second}}").should eq(expected)
end
it 'should parse "Hello `{world}!" as expected' do
expected = \
[:template,
[:fn,
[:strconcat,
[:static, "Hello "],
[:wlang, "`",
[:fn,
[:static, "who"]]],
[:static, "!"]]]]
parse("Hello `{who}!").should eq(expected)
end
it 'is idempotent' do
parse(parse(hello_tpl)).should eq(expected)
end
it 'supports a path-like object' do
parse(hello_path).should eq(expected)
end
it 'supports an IO object' do
hello_io{|io| parse(io)}.should eq(expected)
end
it 'recognizes objects that respond to :to_path' do
s = Struct.new(:to_path).new(hello_path)
parse(s).should eq(expected)
end
it 'recognizes objects that respond to :to_str' do
s = Struct.new(:to_str).new(hello_tpl)
parse(s).should eq(expected)
end
end
end | true |
1f1474bf547530ed540f196515e1cd61d3eab0c6 | Ruby | houcheng/JiebaRuby | /lib/segmenter.rb | UTF-8 | 2,884 | 3.09375 | 3 | [] | no_license | require 'trie'
require 'dag'
require 'dag_dfs'
require 'date'
require 'hmm'
require 'sentence_break_iterator'
SEARCH_SEGMENT_MODE = 1
INDEX_SEGMENT_MODE = 2
class Segmenter
def initialize(args = {})
@segment_mode = args[:segment_mode] || SEARCH_SEGMENT_MODE
@enable_hmm = args[:enable_hmm]
@trie = load_dict_trie
if @enable_hmm
@hmm = Hmm.new
end
end
def process(paragraph)
tokens = []
sentence_break_iterator = SentenceBreakIterator.new(paragraph)
while true
sentence = sentence_break_iterator.next_sentence
break unless sentence
tokens += process_sentence(sentence, sentence_break_iterator.get_posistion)
end
tokens
end
def process_sentence(sentence, sentence_offset)
dag = create_dag(sentence)
dfs = DagDfs.new(dag, @dict)
if @segment_mode == SEARCH_SEGMENT_MODE
max_path = dfs.find_max
tokens = generate_tokens_from_path(max_path, sentence, sentence_offset)
else
tokens = generate_tokens_from_dag(dag, sentence, sentence_offset)
end
process_sentence_with_hmm(sentence, sentence_offset, tokens) if @enable_hmm
tokens
end
private
def process_sentence_with_hmm(sentence, sentence_offset, tokens)
hmm_tokens = @hmm.process_sentence(sentence, sentence_offset)
hmm_tokens.each do |token|
if not tokens.include?(token)
tokens << token
end
end
end
def create_dag(sentence)
dag = Dag.new(sentence)
sentence.length.times.each do |i|
create_dag_substring(dag, sentence[i..-1], i)
end
return dag
end
def create_dag_substring(dag, str, sentence_offset)
node = @trie.get_root
str.length.times.each do |i|
node = node.find_son(str[i])
break unless node
if node.is_word
dag.add_link(sentence_offset, sentence_offset + i + 1) if i > 0
end
end
end
def load_dict_trie
@dict ||= load_dict
trie = Trie.new
@dict.each do |word, freq|
trie.add_word(word, freq)
end
trie
end
def load_dict
dict = {}
File.readlines('conf/sougou.dict').each do |line|
word, freq_string = line.strip.split /[ \t]+/
dict[word] = freq_string.to_i
end
dict
end
# This takes 10% processing time.
def generate_tokens_from_path(max_path, sentence, sentence_offset)
tokens = []
(max_path.length - 1).times do |i|
start_index = max_path[i]
end_index = max_path[i+1] - 1
tokens << [ sentence[start_index..end_index], sentence_offset + start_index ]
end
tokens
end
def generate_tokens_from_dag(dag, sentence, sentence_offset)
tokens = []
dag.end_of_path.times do |i|
links = dag.get_link(i)
links.each do |end_link|
end_index = end_link - 1
tokens << [ sentence[i..end_index], sentence_offset + i ]
end
end
tokens
end
end
| true |
e31f87188314f6fec166f407decc1b0dd17557f6 | Ruby | olbrich/ruby-units | /lib/ruby_units/definition.rb | UTF-8 | 2,965 | 3.328125 | 3 | [
"MIT"
] | permissive | class RubyUnits::Unit < Numeric
# Handle the definition of units
class Definition
# @return [Array]
attr_writer :aliases
# @return [Symbol]
attr_accessor :kind
# @return [Numeric]
attr_accessor :scalar
# @return [Array]
attr_accessor :numerator
# @return [Array]
attr_accessor :denominator
# Unit name to be used when generating output. This MUST be a parseable
# string or it won't be possible to round trip the unit to a String and
# back.
#
# @return [String]
attr_accessor :display_name
# @example Raw definition from a hash
# Unit::Definition.new("rack-unit",[%w{U rack-U}, (6405920109971793/144115188075855872), :length, %w{<meter>} ])
#
# @example Block form
# Unit::Definition.new("rack-unit") do |unit|
# unit.aliases = %w{U rack-U}
# unit.definition = RubyUnits::Unit.new("7/4 inches")
# end
#
def initialize(name, definition = [])
yield self if block_given?
self.name ||= name.gsub(/[<>]/, '')
@aliases ||= (definition[0] || [name])
@scalar ||= definition[1]
@kind ||= definition[2]
@numerator ||= definition[3] || RubyUnits::Unit::UNITY_ARRAY
@denominator ||= definition[4] || RubyUnits::Unit::UNITY_ARRAY
@display_name ||= @aliases.first
end
# name of the unit
# nil if name is not set, adds '<' and '>' around the name
# @return [String, nil]
# @todo refactor Unit and Unit::Definition so we don't need to wrap units with angle brackets
def name
"<#{@name}>" if defined?(@name) && @name
end
# set the name, strip off '<' and '>'
# @param name_value [String]
# @return [String]
def name=(name_value)
@name = name_value.gsub(/[<>]/, '')
end
# alias array must contain the name of the unit and entries must be unique
# @return [Array]
def aliases
[[@aliases], @name, @display_name].flatten.compact.uniq
end
# define a unit in terms of another unit
# @param [Unit] unit
# @return [Unit::Definition]
def definition=(unit)
base = unit.to_base
@scalar = base.scalar
@kind = base.kind
@numerator = base.numerator
@denominator = base.denominator
self
end
# is this definition for a prefix?
# @return [Boolean]
def prefix?
kind == :prefix
end
# Is this definition the unity definition?
# @return [Boolean]
def unity?
prefix? && scalar == 1
end
# is this a base unit?
# units are base units if the scalar is one, and the unit is defined in terms of itself.
# @return [Boolean]
def base?
(denominator == RubyUnits::Unit::UNITY_ARRAY) &&
(numerator != RubyUnits::Unit::UNITY_ARRAY) &&
(numerator.size == 1) &&
(scalar == 1) &&
(numerator.first == self.name)
end
end
end
| true |
dd55a5ebb948fc2ea6d046d7fcb09cf03cd61fb2 | Ruby | emil/hello_world | /linked_list_test.rb | UTF-8 | 893 | 3.203125 | 3 | [] | no_license | require 'minitest/autorun'
require_relative 'linked_list'
class LinkedListTest < MiniTest::Test
def setup
end
def test_find_nth_to_last
ll = LinkedList.new(0)
10.times do |i| ll.add(i+1) end
values = ll.return_list
value_ints = values.map {|n| n.val}
assert_equal 9, ll.nth_to_last(2).val
end
def test_add
l1 = LinkedList.new(3)
[1,5].each {|e| l1.add e}
l2 = LinkedList.new(5)
[9,2].each {|e| l2.add e}
assert_equal [8,0,8], add_lists(l1.head,l2.head).return_list.map {|e| e.val}
end
def add_lists(l1, l2)
carry = 0
ll = nil
while l1 != nil
if ll.nil?
ll = LinkedList.new(l1.val + l2.val + carry)
else
new_carry, val = (l1.val + l2.val).divmod(10)
ll.add(val+carry)
carry = new_carry
end
l1 = l1.next
l2 = l2.next
end
ll
end
end
| true |
2b31b423eb71a2ef36fcb8e7b9d03a1c0614f303 | Ruby | thillerson/learn_ruby | /14_fiftynames/test_data.rb | UTF-8 | 216 | 2.734375 | 3 | [] | no_license | require 'faker'
class TestData
def TestData::create_names(fileName, numNames)
f = File.open(fileName, 'w')
numNames.times {
f.puts "name: " + Faker::Name.name
}
f.close
end
end
| true |
ef2eb934faaafb12b1b809b5b7940ec2fb92a73f | Ruby | jgabrielbc1991/Algoritmo-en-ruby---calculo-de-sumatoria-dado-un-resultado | /preguntavs.rb | UTF-8 | 2,394 | 4.21875 | 4 | [] | no_license | #!/usr/bin/env ruby
puts "Hola, dime la serie de numeros que vamos a comparar. Cuando estes listo escribe 'ya'"
array = [] #Declaramos el array vacio
lista = gets.chomp #Se captura el primer número
array << lista #Se lleva el valor de 'lista' a la ultima posición del array
loop do #Iniciamos el ciclo
puts '¿otro numero?'
lista = gets.chomp
array << lista
lista = array.last #Asignamos a 'lista' el ultimo valor del array
break if lista == 'ya' #Si escribimos 'ya' se detiene el ciclo
end
array.pop #El último 'ya' entra en el array, asi que con pop lo retiramos.
puts "Estos son los numeros que me indicaste #{array}" #se muestran los números en pantalla
puts 'Ahora dime el numero resultado'
resultado=gets.chomp.to_i #Se captura el valor de 'resultado'
puts "El numero resultado que elegiste es #{resultado}" #Se muestra el valor de 'resultado'
array2 = array.map { |x| resultado - x.to_i } #Se crea un nuevo array cuyos numeros son iguales al valor de resultado menos cada uno de los valores del array original. Ej: array=[3,4,8] resultado=12, array2=[9,8,4]
array3 = array.map { |x| x.to_i } & array2.map { |x| x.to_i } #Se crea un tercer array donde se intersectan el primero y el segundo, para obtener los números iguales, Ej: array3=[4,8]
numero1 = array3.map { |x| x.to_i }[0] #Se mapea el tercer array para separar los dos números obtenidos
numero2 = array3.map { |x| x.to_i }[1]
posicion1 = array.map { |x| x.to_i }.index(numero1) + 1 #Se mapea el primer array para determinar la posicion de los dos números obtenidas en el array3 en el primer array.
posicion2 = array.map { |x| x.to_i }.index(numero2) + 1 #Se les suma 1 para darle al usuario la posicion natural y no el indice.
puts "Segun los valores escogidos, los que sumados dan como resultado
#{resultado} estan en las posiciones: #{posicion1} y #{posicion2}" | true |
45b5daa21071a6190d09a866d45f290226d29783 | Ruby | jlgavale/rubyPent | /028_initialize.rb | UTF-8 | 561 | 3.640625 | 4 | [] | no_license | =begin
tiene la caracteristica que es un metodo que se ejecua cuando creamos un objeto de na clase
se utiliza para inicializar valores que el objeto tendra
=end
class Video
attr_accessor :tiempo, :titulo
def initialize(titulo)
#puts "Gracias por iniciar..."
self.titulo = titulo
end
def play
puts "se esta iniciando el video #{titulo}"
end
def stop
puts "Se esta deteniendo el video #{titulo}"
end
end
video1 = Video.new("Curso de Ruby")
#video1.titulo = "curso de ruby"
video1.play
| true |
8e73ceb2f4e9585c33a2504e4dafe62f4b59036c | Ruby | torresga/launch-school-code | /prep_work/ruby_basics/user-input/opposites.rb | UTF-8 | 843 | 4.15625 | 4 | [] | no_license | def valid_number?(number_string)
number_string.to_i.to_s == number_string && number_string.to_i != 0
end
number1 = nil
number2 = nil
loop do
loop do
puts "Please enter a positive or negative integer:"
number1 = gets.chomp
break if valid_number?(number1)
puts "Invalid input. Only non-zero integers are allowed."
end
loop do
puts "Please enter a positive or negative integer:"
number2 = gets.chomp
break if valid_number?(number2)
puts "Invalid input. Only non-zero integers are allowed."
end
if (number1.to_i.positive? && number2.to_i.negative?) || (number1.to_i.negative? && number2.to_i.positive?)
break
else
puts "Sorry. One integer must be positive, another must be negative."
puts "Please start over."
end
end
puts "#{number1} + #{number2} = #{number1.to_i + number2.to_i}"
| true |
453d587a3fd889dddc0fcf807ebf01900ab65500 | Ruby | mble/rainfall-problem | /rainfall_spec.rb | UTF-8 | 591 | 2.84375 | 3 | [] | no_license | require_relative 'rainfall'
require 'rspec'
RSpec.describe 'rainfall' do
subject { Rainfall.new }
it '#calculate works' do
expect(subject.calculate([2, 1, 2])).to eq 1
expect(subject.calculate([5, 0, 5])).to eq 5
expect(subject.calculate([1, 5])).to eq 0
expect(subject.calculate([5, 1])).to eq 0
expect(subject.calculate([2, 5, 1, 2, 3, 4, 7, 7, 6, 3, 5])).to eq 12
expect(subject.calculate([2, 5, 1, 3, 1, 2, 1, 7, 7, 6])).to eq 17
expect(subject.calculate([1, 0, 1])).to eq 1
expect(subject.calculate([2, 5, 1, 2, 3, 4, 7, 7, 6])).to eq 10
end
end
| true |
e8a909642c27f037d74f644a8d5de968326b737e | Ruby | ivopashov/algorithms-data-structures | /sorting/merge_sort.rb | UTF-8 | 1,028 | 4.1875 | 4 | [] | no_license | # central idea is to merge two sorted arrays on every step
# as this is O(n)
# next central idea is to split the collection is such a way that
# you are able to have sorted subarrays. This is done in the recursive step
# until we have 1 item collections which are sorted naturally
def merge(array_a, array_b)
a_index = 0
b_index = 0
result = []
while a_index < array_a.size && b_index < array_b.size do
if array_a[a_index] > array_b[b_index]
result << array_b[b_index]
b_index += 1
else
result << array_a[a_index]
a_index += 1
end
end
(a_index...array_a.size).each { |index| result << array_a[index] }
(b_index...array_b.size).each { |index| result << array_b[index] }
return result
end
def merge_sort(array)
return array if array.size == 1
left_half = merge_sort array[0...(array.size / 2)]
right_half = merge_sort array[(array.size / 2)...array.size]
p "merging #{left_half} #{right_half}"
return merge left_half, right_half
end
p merge_sort [2, 3, 1, 4]
| true |
01a99164081e8445008e57a4e66a8dfb4532e1d8 | Ruby | taratatach/netexport-parser | /parse.rb | UTF-8 | 1,380 | 2.96875 | 3 | [
"MIT"
] | permissive | require 'json'
# Command line helpers
require File.join(File.dirname(__FILE__), '.', 'cmdlinetool')
# Classes
require './models/web_archive'
require './models/har'
require './models/harp'
include Helpers
OPTIONS = [
optdef(:verbose, ["-v", "--verbose"], "print generated json", false),
optdef(:human, "--human", "print result instead of writing to a file", false),
optdef(:csv, "--csv", "generate CSV instead of JSON", false)
]
def run
tty = CmdLineTool.new(OPTIONS)
tty.has_an_arg!
inputname = tty.input
raise "File #{inputname} not found" unless File.file?( inputname )
filetype = (inputname[-1] == "p") ? Harp : Har
export = filetype.new( inputname )
if tty.argindex( "human" )
if tty.argindex( "csv" )
puts export.to_kb.to_csv
else
puts JSON.pretty_generate( export.to_kb, { space: " ", indent: " " } )
end
else
if tty.argindex( "csv" )
output = export.to_csv
extension = "csv"
else
output = export.to_json
extension = "json"
end
outputname = inputname.split('/').last.split('.').first + ".#{extension}"
outputfile = File.open(outputname, "w")
outputfile.write( output )
end
if tty.argindex( "verbose" )
puts "File content:\n"
puts JSON.pretty_generate( export.data, { space: " ", indent: " " } )
end
rescue StandardError => e
puts "Error: #{e}"
end
run
| true |
8b52375d202e082bb0141b03c5dd2408ea0d4a5b | Ruby | radu-constantin/small-problems | /easy2/odd_numbers.rb | UTF-8 | 68 | 2.78125 | 3 | [] | no_license | odd_numbers = (1..99).to_a.select {|num| num.odd?}
puts odd_numbers
| true |
877fdb0a0d82f9eee81b3a66ae40782b0464badf | Ruby | charlottebrf/ruby-kickstart | /session2/challenge/7_array.rb | UTF-8 | 1,490 | 4.0625 | 4 | [
"MIT"
] | permissive | # Given a sentence, return an array containing every other word.
# Punctuation is not part of the word unless it is a contraction.
# In order to not have to write an actual language parser, there won't be any punctuation too complex.
# There will be no "'" that is not part of a contraction.
# Assume each of these charactsrs are not to be considered: ! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / < > ? \ |
#
# Examples
# alternate_words("Lorem ipsum dolor sit amet.") # => ["Lorem", "dolor", "amet"]
# alternate_words("Can't we all get along?") # => ["Can't", "all", "along"]
# alternate_words("Elementary, my dear Watson!") # => ["Elementary", "dear"]
def alternate_words(str)
'!@$#%^&*()-=_+[]:;,./<>?\\|'.split(//).each do |char|
str = str.gsub(char, ' ')
end
alternate_array = []
str.split.map.each_slice(2) do |first, second|
alternate_array << first
end
alternate_array
end
# My solution without checking Josh's & adding in the regex iteration:
#
# def alternate_words(str)
# alternate_array = []
# str = str.gsub(/[[:punct:]]/, '') #couldn't work out how to keep the ' in the string- the rest of this solution is correct
# str.split.map.each_slice(2) do |first, second|
# alternate_array << first
# end
# alternate_array
# end
#
# alternate_words("Can't we all get along?")
# Notes on gsub
# str = str.gsub(/[!@$/[%^&*()-=_+[]:;,./<>?\|]/, '')
# gsub(/[[:punct:]]/, '')
# /\p{P}(?<!')/
# str = str.gsub("(?!) [[:punct:]]", "", str)
| true |
92ea2e013567124da6d7dfa6d8111ba10449b6fd | Ruby | SpiritBreaker226/ruby_fundamentals1 | /exercise3.rb | UTF-8 | 163 | 3.859375 | 4 | [] | no_license | puts "What is your name?"
name = gets.chomp
puts "Hi #{name}!"
puts "What is your age?"
age = gets.chomp
puts "#{name} was born in: #{Time.now.year - age.to_i}" | true |
705a0171c46f39b92a2bf4a630c2d4e4a581afd0 | Ruby | Meloman4eg/kaize_test | /tests/fizzbuzz_test.rb | UTF-8 | 319 | 2.734375 | 3 | [] | no_license | require "test_helper"
class FizzBuzzTest < Minitest::Test
def setup
@test = FizzBuzz.new
end
def test_fizzbuzz
assert_equal @test.fizzbuzz(3), "Fizz"
assert_equal @test.fizzbuzz(50), "Buzz"
assert_equal @test.fizzbuzz(15), "FizzBuzz"
assert_equal @test.fizzbuzz(5175), "FizzBuzz"
end
end | true |
485c8c2a6c4fe2337421405b66fa65b2b1f12495 | Ruby | deloristhompson/learn-oop | /lib/rectangle.rb | UTF-8 | 860 | 3.703125 | 4 | [] | no_license |
class Rectangle
attr_accessor :length, :width, :area, :x, :y, :diagonal
def initialize(length, width, x = nil, y = nil)
@length = length
@width = width
@area = length * width
@x = x
@y = y
@square_root = length * length + width * width
@diagonal = Math.sqrt(@square_root)
if @x.nil? || @y.nil?
@x = 0
@y = 0
end
end
def move_right
@x += 1
end
def move_up
@y += 1
end
def move_left
@x -= 1
end
def move_down
@y -= 1
end
end
# class Rectangle
# attr_reader :length, :width, :area
# def initialize(length, width)
# @length = length
# @width = width
# @area = length * width
#
# end
# end
#
#
# first_rectangle = Rectangle.new(3, 5)
# second_rectangle = Rectangle.new(4, 6)
# puts first_rectangle.area
# puts second_rectangle.area
| true |
b0604400f80fe6f5db9e008d2ab8ad8f370e4206 | Ruby | muroj/oo-tic-tac-toe-bootcamp-prep-000 | /lib/tic_tac_toe.rb | UTF-8 | 3,191 | 4.375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class TicTacToe
WIN_COMBINATIONS = [
[0, 1, 2], # Row wins
[3, 4, 5],
[6, 7, 8],
[0, 3, 6], # Column wins
[1, 4, 7],
[2, 5, 8],
[0, 4, 8], # Diagonal wins
[2, 4, 6]
]
def initialize
@board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
end
#
# Prints the tic-tac-toe board to stdout
#
def display_board()
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end
#
# Converts the user input string to an integer and normalizes to zero-index
#
# @param <user_input> - string containing user input
def input_to_index(user_input)
return user_input.to_i() - 1
end
#
# Enters the specified <player> into the specified position on the board.
#
# @param <move_position> - index of next move, should be in range 0-8
# @param <player> - string with value "X" or "O"
#
def move(move_position, player="X")
@board[move_position] = player
end
#
# Determines whether the specified index represents a valid position on the game board
#
def position_taken?(index)
position = @board[index]
if !(position.nil? || position.eql?(" ") || position.empty?)
return (position.eql?("X") || position.eql?("O"))
else
return false
end
end
#
# Returns true if <index> is a valid position
#
# @param <index> - an integer representing a position on the game board
#
def valid_move?(index)
return index.between?(0, @board.length) && !position_taken?(index)
end
#
# Returns true if <index> is a valid position
#
def turn()
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(index)
move(index, current_player())
display_board()
else
turn()
end
end
#
# Returns the number of turns taken in the current game
#
def turn_count()
turns = 0
@board.each do |position|
if position.eql?("X") || position.eql?("O")
turns += 1
end
end
return turns
end
#
# Returns the current player (next to make a move)
#
def current_player()
# Assume player X goes first
return turn_count() % 2 == 0 ? "X" : "O"
end
def won?()
WIN_COMBINATIONS.each do |winc|
if (@board[winc[0]].eql?("X") && @board[winc[1]].eql?("X") && @board[winc[2]].eql?("X")) || (@board[winc[0]].eql?("O") && @board[winc[1]].eql?("O") && @board[winc[2]].eql?("O"))
return winc
end
end
return false
end
def full?()
@board.all? do |position|
!(position.nil? || position == " ")
end
end
def draw?()
!won?() && full?()
end
def over?()
won?() || draw?()
end
def winner()
win_combo = won?()
win_combo ? @board[win_combo[0]] : nil
end
# Define your play method below
def play()
while !over?()
turn()
end
if won?()
puts "Congratulations #{winner()}!"
elsif draw?()
puts "Cat's Game!"
end
end
end # End TicTacToe class | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.