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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8775600d47bdf1027e6cf8d6898dc79422b92c62 | Ruby | marjielam/codewars-practice | /pig_it.rb | UTF-8 | 459 | 4.125 | 4 | [] | no_license | # Level: 5kyu
# Instructions
# Move the first letter of each word to the end of it, then add 'ay' to the end of the word.
def pig_it text
words = text.split
new_text = ""
words.each_with_index do |word, index|
if word.match(/\W/)
new_text += word
elsif index == words.length - 1
new_text += wo... | true |
0bba701235bb9be71a3eef953de1aba6fe51b2fd | Ruby | kieranfraser/distributedsystems | /Lab4/Client.rb | UTF-8 | 3,143 | 3.65625 | 4 | [] | no_license | ## Simple Client implemented using sockets - sends a
## GET request to the server including some user defined
## text and the server returns the text in all caps.
## It's then printed to the screen to the user.
## @author Kieran Fraser
require "socket"
#Define the hostname and port number to connect to
hostname = "1... | true |
9f6c359eff2c82b93b33216971effe6b5179d196 | Ruby | melzreal/ruby-objects-has-many-lab-v-000 | /lib/author.rb | UTF-8 | 408 | 3.125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Author
attr_accessor :name, :author
def initialize(name)
@name = name
@posts = []
end
def add_post(post_title)
@posts << post_title
post_title.author = self
end
def add_post_by_title(post_title)
posting = Post.new(post_title)
@posts << posting
posting.author = self
... | true |
4a903f90beb18fbb82c7bd1e119411edc38803c4 | Ruby | shyouhei/xmp2assert | /lib/xmp2assert/classifier.rb | UTF-8 | 2,506 | 2.578125 | 3 | [
"MIT"
] | permissive | #! /your/favourite/path/to/ruby
# -*- mode: ruby; coding: utf-8; indent-tabs-mode: nil; ruby-indent-level 2 -*-
# -*- frozen_string_literal: true -*-
# -*- warn_indent: true -*-
# Copyright (c) 2017 Urabe, Shyouhei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and... | true |
35b405b830ec562827aa5ad3c8bcf160a969156f | Ruby | craycode123/41-Anagrams-1-Detecting-Anagrams | /detecting_anagrams.rb | UTF-8 | 595 | 3.859375 | 4 | [] | no_license | # Write your solution here!
=begin
def is_anagram?(word1, word2)
#can also use 'chars' instead of 'split'
word1.downcase.split(//).sort == word2.downcase.split(//).sort
end
=end
def canonical(word)
word = word.downcase.split(//).sort
end
def is_anagram?(word1, word2)
canonical(word1) == canonical(word2)
end
#... | true |
efbce634f680a77b62aacbee6faa7de8b36807f1 | Ruby | RobinWagner/LaunchSchool | /programming_and_back-end_development/programming_foundations/lesson_2/calculator/calculator.rb | UTF-8 | 2,302 | 4.125 | 4 | [] | no_license | # Calculator
require 'yaml'
MESSAGES = YAML.load_file('calculator_messages.yml')
def prompt(message)
Kernel.puts("=> #{message}")
end
def number?(input)
integer?(input) || float?(input)
end
def integer?(input)
/^\d+$/.match(input)
end
def float?(input)
/\d/.match(input) && /^\d*\.?\d*$/.match(input)
end
d... | true |
d5fc61f299b98d7812f13b566b043c875da96c5f | Ruby | rabGIT/assignment_data_structures | /queue.rb | UTF-8 | 1,101 | 3.6875 | 4 | [] | no_license | Node = Struct.new(:data, :next)
# ruby queue implementation
class Queue
def initialize
@first = nil
@last = nil
@len = 0
end
def enqueue(data)
empty? ? new_first(data) : add_node(data)
@len
end
def dequeue
return false if empty?
return finalitem if @len == 1
data = @last.dat... | true |
3ed369d38809597d08f24183e5cb8e921ebc9ff4 | Ruby | UpAndAtThem/practice_kata | /find_it.rb | UTF-8 | 159 | 2.953125 | 3 | [] | no_license | def find_it(seq)
seq.each_with_object(Hash.new(0)) { |int, int_count_hsh| int_count_hsh[int] += 1 }
.find_val { |int, count| count.odd?}
.first
end | true |
91d0af0c3eac099fb91e43fd493953b5e6b40b7e | Ruby | danpaulgo/s_and_p_analyzer | /lib/sp500_analyzer/data_point.rb | UTF-8 | 1,273 | 3.1875 | 3 | [] | no_license | require_relative "../../config/environment.rb"
class DataPoint
@@all = []
attr_accessor :id, :date, :price, :monthly_change, :yearly_change, :historical_max, :max_date
def initialize
@@all << self
end
def self.all
@@all
end
def previous_month
year = date.year
month = date.month
... | true |
3387bd7f8d262af47b46041f46de44362d1d9ce2 | Ruby | hyuraku/Project_Euler | /section5/problem43.rb | UTF-8 | 403 | 3.125 | 3 | [] | no_license | arr = (0..9).to_a
max = 10
aa = arr.permutation(max).map do |a|
(a.join).to_i
end
aa = aa.select { |a|
a > (10 ** 9)
}
primes = [17,13,11,7,5,3,2]
sum = 0
aa.each do |a|
res = true
primes.each.with_index(0) do |prime, index|
target = a% (10**(index+3)) / (10**(index))
if (target%prime != 0)
re... | true |
74767db9d06d2099812b7519affcf597f972bdde | Ruby | jasonmiles/introduction_to_programming | /medquiz1_question2.rb | UTF-8 | 213 | 2.71875 | 3 | [] | no_license | #Looked at your solution(ashamedly).
result = {}
letters = ('A'..'Z').to_a.concat( ('a'..'z').to_a )
letters.each do |letter|
count = statement.scan(letter.to_s).count
result[letter] = count if count > 0
end | true |
6c9ac0867f907f476159f1e4baf3389dbe8e9eab | Ruby | paulo-techie/code-wars-ruby-solutions | /last_digit_of_huge_number.rb | UTF-8 | 4,945 | 3.171875 | 3 | [] | no_license | # def last_digit(lst)
# return 1 unless lst[0]
# return 1 if lst.size == 2 && lst.all?{|n| n==0 }
# return 1 if lst.size < 2 && lst[0] < 1
# return 0 if lst.all?{|n| n==0 }
# return (lst[-2]**lst[-1]).digits.first if lst.size < 3
# return lst.reverse.reduce{|a, b| b**a}.digits.first if lst.all?{|n| n<10}
... | true |
9c949fbc3325d9514c907e8848f8df705c164629 | Ruby | Calvin0125/ruby-caesar-cipher | /caesar.rb | UTF-8 | 771 | 3.640625 | 4 | [] | no_license | print "enter a word \n"
user_word = gets.chomp
print "enter a shift factor \n"
shift = gets.chomp
if shift.to_i < 0
shift = shift.to_i * -1
shift = shift % 26
shift = shift.to_i * -1
p shift
elsif shift.to_i > 0
shift = shift.to_i % 26
end
p shift
user_array = user_word.split('')
char_codes = user_a... | true |
1dbf384f0c89e86a663195c72da6adf56b064fdd | Ruby | jsanchy/launch-school-exercises | /small_problems_ruby/easy1/array_average.rb | UTF-8 | 711 | 4.8125 | 5 | [] | no_license | =begin
examples:
puts average([1, 5, 87, 45, 8, 8]) == 25
puts average([9, 47, 23, 95, 16, 52]) == 40
inputs:
non-empty array of positive integers
output:
average of the numbers in the input array
algorithm:
create variable to keep track of sum, intialize to 0
loop through input array
add element t... | true |
79b82f57de0d55ad46f69fea538dd3864d1bee93 | Ruby | itb2/Code20402017 | /code2040techAsess.rb | UTF-8 | 2,491 | 2.578125 | 3 | [] | no_license | ________________Step1________________________________________________________________
require "http"
#My API Token: 8eacb8876d3324b2748d6f649cc15770
#Github: https://github.com/itb2/Code20402017.git
#reg endpoint: http://challenge.code2040.org/api/register
response = HTTP.post("http://challenge.code2040.org/api/regi... | true |
b5f1087ed680a0914b0fd1e22296309a3a33d405 | Ruby | AkeelAli/Depot2 | /app/models/cart.rb | UTF-8 | 482 | 2.8125 | 3 | [] | no_license | class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity +=1
else
current_item= line_items.build(:product_id=>product_id)
end
current_item
end
def tot... | true |
95dd28f2fc11edd2398dde91ad37f8423a3e8e19 | Ruby | thuyihan1206/algorithms | /trees/binary_search_tree.rb | UTF-8 | 3,478 | 3.765625 | 4 | [] | no_license | # frozen_string_literal: true
require_relative './binary_tree'
# Class for a binary search tree
class BinarySearchTree < BinaryTree
def add_node(value, local_root = @root)
if local_root.nil?
local_root = Node.new(value)
@root ||= local_root # set root for the tree
else
case value <=> local... | true |
23e20a7168f0e2cb448cccb9bd37778596b78e3d | Ruby | descentintomael/include_date_scopes | /lib/include_date_scopes/date_scopes.rb | UTF-8 | 1,911 | 2.703125 | 3 | [
"MIT"
] | permissive | # Add the below date based scopes to a model.
#
# between(start_date_or_time, stop_date_or_time)
# on_or_before(date)
# before(date)
# on_or_after(date)
# after(date)
# on(date)
# day(date)
# last_24_hours() * DateTime only
# last_hour() * DateTime only
# last_week()
# last_month()
# tod... | true |
21d0613692dc4cc260a9102b9a218db0bcefcf2b | Ruby | jonstafford/chess | /lib/board.rb | UTF-8 | 3,778 | 3.59375 | 4 | [
"MIT"
] | permissive | require_relative 'colors'
require_relative 'move_syntax_validation'
require_relative 'king'
class Board
include Colors
attr_reader :layout
def initialize(layout)
# @layout is an array of row arrays. So location [x, y] is at @layout[y][x].
@layout = layout
end
# Answers an array of lines whic... | true |
0ff16fb16208f5b354ff664af1505efd6eddd179 | Ruby | zachjamesgreen/SweaterWeather | /app/lib/current_weather.rb | UTF-8 | 1,012 | 2.921875 | 3 | [] | no_license | class CurrentWeather
attr_reader :datetime, :sunrise, :sunset, :temperature, :feels_like, :humidity, :uvi, :visibility, :conditions, :icon
def initialize(info)
@datetime = Time.at(info['current']['dt'])
@sunrise = Time.at(info['current']['sunrise'])
@sunset = Time.at(info['current']['sunset'... | true |
36b754990b893064adfeb662331a8c19db349385 | Ruby | ssjuampi23/sample_app | /spec/requests/user_pages_spec.rb | UTF-8 | 9,073 | 2.625 | 3 | [] | no_license | require 'spec_helper'
describe "UserPages" do
subject { page }
describe "signup page" do
before { visit signup_path }
it { should have_selector_h1("Sign up")}
it { should have_selector_title("Sign up")}
end
describe "profile page" do
let(:user){ FactoryGirl.create(:user) }#code to ... | true |
4604ff67c68e33f56ced82c27931d945f57d501f | Ruby | nkrsudha/neutral | /spec/dummy/config/initializers/neutral.rb | UTF-8 | 1,421 | 2.5625 | 3 | [
"MIT"
] | permissive | #Neutral engine Initializer
Neutral.configure do |config|
# Set to false wheter a voter cannot change(i.e. update or delete) his vote.
#config.can_change = true
# Configure method providing a voter instance.
# Also make sure your current voter method is accessible from your ApplicationController
# as a help... | true |
2005fd5c7c53302a3c212121ba4eae0477761742 | Ruby | eddygarcas/vortrics | /app/models/montecarlo.rb | UTF-8 | 595 | 3.03125 | 3 | [
"MIT"
] | permissive | class Montecarlo
attr_writer :number, :backlog, :focus, :iteration
def number
@number ||= 1000
end
def backlog
@backlog ||= 50
end
def focus
(@focus ||= 100).to_f / 100
end
def iteration
@iteration ||= 5
end
def initialize(params = {})
return unless params.dig(:montecarlo).p... | true |
70af9e6e6ac1adb8951953c45464f465c5f38c45 | Ruby | d3r1v3d/frisco-beer-crawler | /lib/frisco_beers.rb | UTF-8 | 449 | 2.796875 | 3 | [] | no_license | require 'mechanize'
module Frisco
def self.beers
spider = Mechanize.new { |agent|
agent.user_agent_alias = 'Windows Mozilla'
}
beers = []
page = spider.get('http://friscogrille.com/beers.php')
page.search('#keg-beers > ul li').each do |beer|
beers << beer.text
end
puts "Fris... | true |
b19750c0f9de031e06b4dfd5f1e191c1b1ffc7d6 | Ruby | GenSplice-Research-Development/version | /Chromosome Variation/Somys/nullisomy.rb | UTF-8 | 916 | 3.1875 | 3 | [] | no_license | def Nullisomy(b, a = 0)
eu = b #Even number
chrom = a #Chromosome number
return "only even numbers permitted" if eu.odd? == true
set = {2 => "||"}
if chrom == 0
hap = eu/2 #Creates haploid number
diploid = [2] * hap #Creates Karyotype
chromo_number = [*0..(diploid.count-1)].sample(1).po... | true |
22603f627899b494bf0be23affc54771ab0480ca | Ruby | MrRogerino/ClapOnce-API | /app/controllers/users_controller.rb | UTF-8 | 2,080 | 2.859375 | 3 | [] | no_license | class UsersController < ApplicationController
include UsersHelper
def notify_users
epicenter = [params[:lat].to_i, params[:long].to_i]
severity = params[:severity]
@users = alert_users(epicenter, severity)
render json: {users: @users}.as_json, status: 201
end
def show
@user = User.find_by... | true |
07b77b8d1f59ba8e408001eaf59f553920ce624f | Ruby | tony-gomes/futbol | /lib/game.rb | UTF-8 | 2,795 | 3.21875 | 3 | [] | no_license | class Game
@@games = {}
def self.add(game)
@@games[game.game_id] = game
end
def self.all
@@games
end
def self.number_of_games
@@games.length
end
def self.all_seasons
seasons = @@games.values.reduce([]) do |acc, game|
acc << game.season
end
seasons.uniq
end
def self... | true |
29345e0d96668795052945eb57c7cfdcf5d571d3 | Ruby | carlosadr11/Aplicaciones-WEB | /ruby/Tesoro.rb | UTF-8 | 401 | 3.5625 | 4 | [] | no_license | class Tesoro
def get_nombre
return @nombre
end
def set_nombre(nombre)
@nombre=nombre
end
def get_descripcion
return @descripcion
end
def set_nombre(descripcion)
@descripcion=descripcion
end
def to_s #sobreescribir el metodo por defecto to_s
"El tesoro #{@nombre} es #{@descripcion}\n"
end
en... | true |
3f2d6408861da730004d6aebab4fe3ecd6580f7e | Ruby | yusuke0024/barbar_guide_app | /spec/system/user_spec.rb | UTF-8 | 3,700 | 2.53125 | 3 | [] | no_license | require "rails_helper"
RSpec.describe "User", type: :system do
describe "ユーザー登録機能" do
before do
#新規ユーザー登録ページ
visit new_user_path
#正常範囲の入力値を入力
fill_in "user_name", with: "yusuke"
fill_in "user_email", with: "example@mail.com"
fill_in "user_password", with: "foobar"
end
... | true |
8233e3896e574511429b226f1cd9bc9e5d1f767f | Ruby | chrismear/rails-lighthouse-archive | /data/attachments/103259/batches.rb | UTF-8 | 4,104 | 2.921875 | 3 | [
"MIT"
] | permissive | module ActiveRecord
module Batches # :nodoc:
def self.included(base)
base.extend(ClassMethods)
end
# When processing large numbers of records, it's often a good idea to do so in batches to prevent memory ballooning.
module ClassMethods
# Yields each record that was found by the find +opti... | true |
e68ff88f40a7a1e1ebe1669429955ce1764057e7 | Ruby | katguz3485/ruby-101-challenges | /04-Merge-and-sort-array/spec/merge_and_sort_array_spec.rb | UTF-8 | 332 | 2.5625 | 3 | [] | no_license | require_relative '../lib/merge_and_sort_array'
describe '#merge_and_sort_array' do
it 'should return an Array' do
expect(merge_and_sort_array(['B', 'C'], ['A', 'D'])).to be_a(Array)
end
it 'should return one sorted array' do
expect(merge_and_sort_array(['B', 'C'], ['A', 'D'])).to eq(['A', 'B', 'C', 'D']... | true |
1aaa71ccc7718679cd63bc90c9ae2d668092e122 | Ruby | lastobelus/merb_global | /lib/merb_global/locale.rb | UTF-8 | 4,604 | 3.015625 | 3 | [
"MIT"
] | permissive | require 'merb_global/base'
require 'thread'
require 'weakref'
class Thread
attr_accessor :mg_locale
end
module Merb
module Global
class Locale
attr_reader :language, :country
def initialize(name)
# TODO: Understand RFC 1766 fully
@language, @country = name.split('-')
end
... | true |
15956802368623c8b5592fb6300d975f095be900 | Ruby | devmichaelmcf/launchschool | /RB101/small_problems/easy1/sum_of_digits.rb | UTF-8 | 866 | 4.75 | 5 | [] | no_license | # Write a method that takes one argument, a positive integer, and returns the sum of its digits.
=begin
Problem: Take a Integer. Return the total of its visible digits.
Examples: Big num digits the method ignores the underscores. Input and output are integers.
Data structure: Array as a single ordered list should be s... | true |
67203063856321f91f48c3064c7af51aeaf3c682 | Ruby | thomasstephane/flashquizz | /app/models/game.rb | UTF-8 | 976 | 2.875 | 3 | [] | no_license | class Game < ActiveRecord::Base
belongs_to :user
belongs_to :deck
validates :user_id, :deck_id, :presence => true
after_initialize :init
def init
self.cards_shown ||= 0
self.cards_correct ||= 0
end
def score
p self.cards_shown
if self.cards_shown == 0
0
else
p @score = ((self.ca... | true |
30dc15424f71cb5095f66c9bef5bb205d76641a7 | Ruby | Dahie/caramelize | /lib/caramelize/caramel.rb | UTF-8 | 2,461 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'caramelize/input_wiki/wikkawiki'
require 'caramelize/input_wiki/redmine_wiki'
## Example caramelize configuration file
# Within this method you can define your own Wiki-Connectors to Wikis
# not supported by default in this software
# Note, if you want to activate this, you need to uncomment the line below.... | true |
a8db72db89c80eef752e590585bae3731c084c09 | Ruby | bdurand/sunspot_index_queue | /lib/sunspot/index_queue.rb | UTF-8 | 7,168 | 2.796875 | 3 | [
"MIT"
] | permissive | module Sunspot
# Implementation of an asynchronous queue for indexing records with Solr. Entries are added to the queue
# defining which records should be indexed or removed. The queue will then process those entries and
# send them to the Solr server in batches. This has two advantages over just updating in plac... | true |
9316412464b4ccd5a491ead1ba03792263cda84e | Ruby | ldlsegovia/organizer | /lib/organizer/source/collection.rb | UTF-8 | 551 | 2.625 | 3 | [
"MIT"
] | permissive | module Organizer
module Source
class Collection < Array
include Organizer::Error
include Organizer::Collection
include Organizer::Explainer
collectable_classes Organizer::Source::Item
def fill(_raw_collection)
raise_error(:invalid_collection_structure) unless _raw_collectio... | true |
24f1fee9949103e1a4aebcbd93ef7ecbdc26eb0f | Ruby | SudoEvrything/rubytuto | /the_odin_project/mastermind.rb | UTF-8 | 4,511 | 3.84375 | 4 | [] | no_license | class Mastermind
def initialize
@board = Board.new
@player = Player.new('Player', @board)
@computer = Computer.new('Computer', @board)
@current_player;
end
def start_game
loop do
puts "Which role do you want to play?"
puts "1. Codemaker 2. Codebreaker"
puts "Please select 1 ... | true |
ab09f552e1b4508604519086d3a13e93533c05f0 | Ruby | liaden/shokugeki | /spec/models/ingredient_graph_spec.rb | UTF-8 | 4,625 | 2.515625 | 3 | [] | no_license | describe IngredientGraph do
let(:graph) { IngredientGraph.new(search) }
let(:search) { build(:search_ingredient) }
let(:pair) { create(:ingredient_pairing, occurrences: 2) }
let(:zero_occurrence) { create(:ingredient_pairing, ingredients: [pair.first_ingredient, create(:ingredient, name: 'z')]) }
let(:hidden_... | true |
2ffc225628a1a8b8177dfb7b16532bbba2010af9 | Ruby | iamjarvo/timelog | /features/step-definitions/timelog_steps.rb | UTF-8 | 208 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'time'
Given /^the time is (\d+:\d+)$/ do |time|
@time = Time.parse(time)
end
Given /^(\d+) minutes has passed$/ do |minute_count|
seconds = minute_count.to_i * 60
@time = @time + seconds
end
| true |
c357863481d291ac824f1cbf890bed5e2aeab763 | Ruby | kenta-s/atcoder | /abc120/c02.rb | UTF-8 | 181 | 3.234375 | 3 | [] | no_license | s = gets.chomp.chars
stack = []
ans = 0
s.each do |c|
if stack.empty?
stack << c
elsif stack[-1] == c
stack << c
else
stack.pop
ans += 2
end
end
puts ans
| true |
4efc128bb58eaba5e681942af2d0b8a1e794c9ed | Ruby | sstelfox/patronus_fati | /lib/patronus_fati/event_handler.rb | UTF-8 | 806 | 2.671875 | 3 | [
"MIT"
] | permissive | module PatronusFati
class EventHandler
def handlers
@handlers ||= {}
end
def handlers_for(asset_type, event_type)
handlers[asset_type] ||= (asset_type == :any ? [] : {})
Array(handlers[:any]) | Array(handlers[asset_type][:any]) | Array(handlers[asset_type][event_type])
end
def ... | true |
46a76b3c8bf871c8299c54177889d59f9acc5b8c | Ruby | konkit/konkit_worklogger | /lib/konkit_worklogger/printer.rb | UTF-8 | 1,398 | 3.515625 | 4 | [
"MIT"
] | permissive | class DaySummaryPrinter
def initialize(configuration)
@configuration = configuration
end
def print(year, month, day)
entry = DayEntryLoader.new(@configuration).load_from_file(year, month, day)
date_string = format('%d-%02d-%02d', year, month, day)
puts format('%s: %s - %s (%s)', date_string, ent... | true |
3b96180b7ed6501b75696b510c0b31719813302b | Ruby | AviZurel/evigilo | /scrubber.rb | UTF-8 | 313 | 2.625 | 3 | [
"MIT"
] | permissive | class Scrubber
def initialize(app)
@app = app
end
def call(env)
scrub(env)
@app.call(env)
end
def scrub(env)
rack_input = env['rack.input'].read.force_encoding(Encoding::UTF_8)
env.update('rack.input' => StringIO.new(rack_input))
ensure
env['rack.input'].rewind
end
end
| true |
9433f064a700089cf9c34c030f18c9ddad795baf | Ruby | wulman16/sinatra-nested-forms-lab-superheros-atlanta-web-career-012819 | /app/models/team.rb | UTF-8 | 233 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Team
attr_reader :name, :motto
@@all = []
def initialize(name, motto)
@name = name
@motto = motto
@@all << self
end
def self.all
@@all
end
def members
Hero.all.select { |hero| hero.team == self }
end
end | true |
19a918d934e192d5cabf47ff06d41cf06e40cdd0 | Ruby | vprokopchuk256/algorithms | /spec/lib/algorithms/custom/lru_cache.rb | UTF-8 | 1,257 | 2.5625 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe Algorithms::Custom::LRUCache do
let(:capacity) { 2 }
subject(:cache) { described_class.new(capacity) }
describe '#initialize' do
its(:capacity) { is_expected.to eq(capacity) }
end
it 'ex1' do
cache.put(1, 1)
cache.put(2, 2)
expect(cache.get(1)).to eq(1)... | true |
59811985b32ef481fe95b65d78c0282bb966267d | Ruby | takeshy/mongorilla | /lib/mongorilla/cursor.rb | UTF-8 | 895 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Mongorilla
class Cursor
include Enumerable
def [](idx)
if idx < 0
idx = @cursor.count + idx
return nil if idx < 0
else
return nil if idx >= @cursor.count
end
return @members[idx] if @members[idx]
ret = @cursor.skip(idx).limit(1).first
@cursor... | true |
a9194dd99e24f3c365714bcbe704d704a3235b30 | Ruby | luislaugga/bonekit | /examples/analog/potentiometer.rb | UTF-8 | 475 | 3.125 | 3 | [
"MIT"
] | permissive | # Potentiometer
#
# This example shows how to control the brightness of an LED using a potentiometer.
#
# The circuit:
# * LED with 180 ohm resistor attached from pin P9_42 to DGND.
# * Potentiometer attached to pin P9_39, VDD_ADC and GNDA_ADC.
#
require 'bonekit'
led = Pin.new P9_42 # LED connected to a pin that sup... | true |
ee25172a0de93523894702606cd9291689ee0f1f | Ruby | christianreyes/272 | /notes/mp_lectures_2011/discounter/discounter_9.rb | UTF-8 | 1,331 | 3.234375 | 3 | [] | no_license | # discounter_9.rb
#
# Creating memoization writing a DSL in a block
# Based off original example by Dave Thomas (2008)
module Memoize
def remember(name, &block)
memory = Hash.new
define_method(name, &block)
meth = instance_method(name)
define_method(name) do |*args|
if memo... | true |
4c738b17810d3bca9da2c28c85771a7e1bdc836d | Ruby | dsisnero/power-panel | /lib/power/breaker.rb | UTF-8 | 1,338 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'virtus'
require File.join(File.dirname(__FILE__), 'slot')
module Power
class ABreaker
include Virtus
attribute :description, String
attribute :amps, Integer, :default => 20
def initialize(*args)
super(*args)
end
def to_array
[ number, description,amps]
end
end... | true |
d10b3414a0ce0649878564bd5b9d6255aadba4ad | Ruby | mattmanning/adventofcode2020 | /02/b.rb | UTF-8 | 304 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env ruby
total = File.open('input').inject(0) do |sum, line|
cols = line.split(' ')
positions = cols[0].split('-').map(&:to_i)
letter = cols[1].split(':')[0]
if (cols[2][positions[0]-1] == letter) ^ (cols[2][positions[1]-1] == letter)
sum + 1
else
sum
end
end
puts total
| true |
03427b2d83b504722cfcfca27652e949e79aaae5 | Ruby | tommcgee/tictactoe_sinatra | /lib/presenters/message_presenter.rb | UTF-8 | 279 | 2.703125 | 3 | [] | no_license | require_relative '../sinatra_ui'
class MessagePresenter
@ui = Sinatra_UI.new
def self.get_status_message(board)
if board.over
@ui.print_winner(board)
else
@ui.print_player_turn
end
end
def self.get_games_completed()
@ui.print_games_completed()
end
end | true |
4586c409d5595997b73e48055cc083ff0858f103 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/word-count/5e854363948a468a96241e1703231f29.rb | UTF-8 | 319 | 3.46875 | 3 | [] | no_license | class Phrase
def initialize(text)
@text = text
end
def word_count
word_groups = parse_words.group_by{|x| x}
words_with_count = word_groups.map{|word, word_group| [word, word_group.length]}
Hash[words_with_count]
end
private
def parse_words
@text.scan(/\w+/).map(&:downcase)
end
end
| true |
294a0a8adf55445b3eaa10c817e9a24fcc22632a | Ruby | sarahhay7/ruby_talk_2019 | /csv_examples/blank_csv.rb | UTF-8 | 267 | 2.84375 | 3 | [] | no_license | require 'csv'
require 'fileutils'
FileUtils.touch('new_csv.csv')
puts "csv = CSV.open('new_csv.csv')"
csv = CSV.open('new_csv.csv')
puts "csv.class: #{csv.class}"
puts "csv.read: #{csv.read}"
puts "csv.read.class: #{csv.read.class}"
FileUtils.rm('new_csv.csv') | true |
c1d4a884aff8083b102b48b3e90d36b302985ddd | Ruby | Steveo00/launchschool | /ruby_basics/user_input/exercise_7.rb | UTF-8 | 330 | 3 | 3 | [] | no_license | USER_NAME = 'SteveO'
PASSWORD = 'plucker'
loop do
puts "Please enter your user name:"
user_name_response = gets.chomp
puts "Please enter your password:"
password_response = gets.chomp
break if ( user_name_response == USER_NAME ) && ( password_response == PASSWORD )
puts "Authorization failed."
end
puts "W... | true |
1c436511a667edc0f64a75ca60d642a94dc51e28 | Ruby | ejbyne/ruby-mars-rovers | /spec/plateau_spec.rb | UTF-8 | 2,611 | 3.28125 | 3 | [] | no_license | require_relative '../app/models/plateau'
describe Plateau do
let(:plateau) { Plateau.new({ max_coords: '5 5', cell_class: cell_class }) }
let(:cell_class) { double :cell_class, new: cell }
let(:cell) { double :cell }
let(:rover) { double :rover }
context 'creating a grid' do
it '... | true |
1bf2810e588dd4b7184c3e2800d6ff9102a592ce | Ruby | manbc/Ruby | /dfs.rb | UTF-8 | 1,376 | 3.765625 | 4 | [] | no_license | #depth first search implementation
$order = 0
def depth_first_search(matrix, vertices_array, vertex)
$order += 1
vertices_array[vertex] = $order
for i in 0...matrix.length
# if there is an edge and the vertex is not visited
if (matrix[vertex][i] == 1 && vertices_array[i] == 0)
depth_first_search(mat... | true |
9da00bdd63474b52a38a4e7170616464ddff0c11 | Ruby | aidanmc95/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-sea01-seng-ft-042020 | /nyc_pigeon_organizer.rb | UTF-8 | 426 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
pigeon_list = {}
data.each do |key1, value1|
value1.each do |key2, value2|
value2.each do |value3|
if pigeon_list[value3] == nil
pigeon_list[value3] = {}
end
if pigeon_list[value3][key1] == nil
pigeon_list[value3][key1] = []
... | true |
6351f8d09c9cb9fe8d1c8c98e0a447e68157e378 | Ruby | mizutaki/crawler | /chapter1/sbcr1.rb | UTF-8 | 396 | 2.78125 | 3 | [] | no_license | require 'cgi'
def parse(page_source)
dates = page_source.scan(%r!(\d+)年 ?(\d+)月 ?(\d+)日<br />!)
url_titles = page_source.scan(%r!^<a href="(.+?)">(.+?)</a><br />!)
url_titles.zip(dates).map{|(aurl, atitle),
ymd|[CGI.unescapeHTML(aurl),CGI.unescapeHTML(atitle),
Time.local(*ymd)]
}
end
x = parse(`/usr/lo... | true |
df399a8e8d47afa276e9f4b708e3eb4e20ead445 | Ruby | vecchp/sevenlanguages | /Ruby/Day 2/1.rb | UTF-8 | 305 | 3.9375 | 4 | [] | no_license | # Print the contents of an array. of sixteen numbers,
a = (1..16).to_a
## Four at a time, using just each.
tmp = []
a.each { |x|
tmp.push(x)
puts tmp.join(' '), tmp = [] if tmp.size % 4 == 0
}
puts tmp.join(' ') if tmp.size > 0
## With each_slice in Enumerable
a.each_slice(4){ |slice| p slice} | true |
fde57a58f8212d773fa14b88bedddb3776fa11a0 | Ruby | tmekkelisti/eventmanager | /app/models/event.rb | UTF-8 | 873 | 2.5625 | 3 | [] | no_license | class Event < ApplicationRecord
belongs_to :user
belongs_to :location
has_many :participations
has_many :participants, :through => :participations, :source => :user
has_many :comments, as: :commentable
validates :name, length: { minimum: 3 }
validates :description, length: { maximum: 500 }
validates ... | true |
00c86e3eda66b09222331493c046a9991dcb74b8 | Ruby | l0v1s/yelp_clone | /spec/features/reviews_feature_spec.rb | UTF-8 | 911 | 2.609375 | 3 | [] | no_license | require 'rails_helper'
describe 'restaurant reviews' do
before do
Restaurant.create(name: "Wasabi", description: "Sushi and Asian food")
end
def leave_review(thoughts, rating)
visit '/restaurants'
click_link 'Add a review for Wasabi'
fill_in "review_thoughts", with: thoughts
select rating, :f... | true |
7d9c8c38dffd6a306d5ed59b5bf7d6507b8e8d94 | Ruby | itggot-josef-andersson/master-ejaculator | /scenes/pause_scene.rb | UTF-8 | 570 | 2.6875 | 3 | [] | no_license | require_relative './scene'
require_relative '../handlers/game_handler'
require_relative '../enums/z_order'
require_relative '../enums/scene_id'
class PauseScene < Scene
def initialize
@font = Gosu::Font.new(25)
@keyboard_handler = GameHandler.get_instance.keyboard_handler
end
def update
return Sce... | true |
35045b09f13b7379964a70778c78243212c78b0a | Ruby | jzaleski/hijack | /app/scripts/dragonrealms/juggle_script.rb | UTF-8 | 1,271 | 2.671875 | 3 | [] | no_license | load "#{SCRIPTS_DIR}/base/base_dragonrealms_script.rb", true
class JuggleScript < BaseDragonrealmsScript
ITS_EASIER_TO_JUGGLE = "It's easier to juggle"
YOU_CANNOT_JUGGLE = 'You cannot juggle'
YOU_TOSS = 'You toss'
JUGGLE_FAILURE_PATTERN = [
ITS_EASIER_TO_JUGGLE,
YOU_CANNOT_JUGGLE,
].join('|')
JUG... | true |
67aa339d4c9481b2185b726a506ab9fdf182e16b | Ruby | msgpack/msgpack-ruby | /spec/cruby/buffer_io_spec.rb | UTF-8 | 4,694 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'random_compat'
require 'stringio'
if defined?(Encoding)
Encoding.default_external = 'ASCII-8BIT'
end
describe Buffer do
r = Random.new
random_seed = r.seed
puts "buffer_io random seed: 0x#{random_seed.to_s(16)}"
let :source do
''
end
def set_source(s)
source.repl... | true |
93a84e2a2e59dd2d703f99ebfc4c61b179e403ed | Ruby | diegoarvz4/lexi-series | /app/helpers/series_helper.rb | UTF-8 | 251 | 2.625 | 3 | [
"MIT"
] | permissive | module SeriesHelper
def count_episodes(series)
series.episodes.all.count
end
def instructions(inst)
inst.gsub(/\s\s+/, "").split("+").reject{|n| n==""}
end
def sorted_episodes
@series.episodes.sort_by{|ep| ep.number}
end
end
| true |
140950477d7048a09cb4446b37e9e3c6f0c07d4d | Ruby | cgullickson/cg-cli-app | /lib/upcoming/concert.rb | UTF-8 | 365 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'pry'
class Upcoming::Concert
attr_accessor :artist, :showtime, :price, :ticket_url, :location
@@all = []
def initialize(artist, showtime, price, ticket_url, location)
@artist = artist
@showtime = showtime
@price = price
@ticket_url = ticket_url
@location = location
@@all << sel... | true |
1db28a3a7d5608f8a22b2279f858e5bc63b7a794 | Ruby | jho406/dbc_anagrams | /app/controllers/index.rb | UTF-8 | 1,041 | 3.375 | 3 | [] | no_license | get '/' do
if params[:word]
# If we see a URL like /?word=apples redirect to /apples
#
# The HTTP status code 301 means "moved permanently"
# See: http://www.sinatrarb.com/intro#Browser%20Redirect
# http://en.wikipedia.org/wiki/HTTP_301
redirect to("/#{params[:word]}"), 301
else
# L... | true |
eb96a93be9b7df86012c590a91ac0a0265baa978 | Ruby | alansparrow/learningruby | /classeval1.rb | UTF-8 | 460 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env ruby
class Class
def add_accessor(accessor_name)
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
class Person
end
person = Person.new
Person.add_accessor :name
Person.add_accessor :gender
person.name = "Peter Cooper"
person.gender = "male"
puts "#{person.name} is #{perso... | true |
c8505db0f35b6ee4bcee4ca650b28d675428e0c1 | Ruby | scottcmerritt/custom_sort | /lib/custom_sort/magic.rb | UTF-8 | 1,980 | 2.546875 | 3 | [] | no_license | require "i18n"
module CustomSort
class Magic
attr_accessor :query_name, :options
def initialize(query_name:, **options)
@query_name = query_name
@options = options
end
def self.validate_period(period, permit)
permitted_periods = ((permit || CustomSort::FIELDS).map(&:to_sym) & ... | true |
912b33895747b74b35483749349fc4916dfc9a86 | Ruby | srikanthgurram/TimeSheets | /db/seeds.rb | UTF-8 | 1,272 | 2.53125 | 3 | [] | no_license |
# Companies
if !(Company.count > 0)
Company.create(name: "Company ABC");
Company.create(name: "Company XYZ");
else
puts "Companies table is not Empty, skipping seed data"
end
# Clients
if !(Client.count > 0)
Client.create(name: "Client DE", company_id: Company.find_by(name: 'Company ABC').id);
Client.create... | true |
95e6126afdd7410df130e11f421bfc0ca2a184d4 | Ruby | beauby/jsonapi-validations | /lib/jsonapi/validations/relationship.rb | UTF-8 | 1,949 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'jsonapi/parser'
module JSONAPI
module Validations
module Relationship
module_function
# Validate the types of related objects in a relationship update payload.
#
# @param [Hash] document The input JSONAPI document.
# @param [Hash] params Validation parameters.
# @o... | true |
2b037e589a22eb66cd212d66b28dbbac91407037 | Ruby | ekemi/school-domain-onl01-seng-ft-012120 | /lib/school.rb | UTF-8 | 646 | 3.359375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
require "pry"
class School
def initialize(name)
@name = name
@roster ={}
end
def roster
@roster
end
def add_student (student_name, student_grade)
@roster [student_grade] ||=[]
@roster[student_grade] << student_name
# binding.pry
end
def grade (leve... | true |
2726ab1a915c0632f05f5c5618f6de4a1c44f9d3 | Ruby | SethMusulin/Intro_to_tdd | /spec/num_calc_spec.rb | UTF-8 | 844 | 3.125 | 3 | [
"MIT"
] | permissive | require 'num_calc'
describe NumCalc do
it"has a method that returns the sum of two numbers" do
calc = NumCalc.new
expected = 3
actual = calc.add(2,1)
expect(actual).to eq expected
end
it" has a method that returns the difference of two numbers" do
calc = NumCalc.new
expected = 1
ac... | true |
e586c3216aa3f0fe5cd64fbfb01a46ef5279549a | Ruby | hai-nguyen1112/simple-math-dc-web-career-01719 | /lib/math.rb | UTF-8 | 533 | 3.359375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def addition(num1, num2)
return num1 + num2
end
addition(5, 4)
def subtraction(num1, num2)
return num1 - num2
end
subtraction(10, 5)
def division(num1, num2)
return num1 / num2
end
division(50, 2)
def multiplication(num1, num2)
return num1 * num2
end
multiplication(4, 30)
def modulo(num1, num2)
return num1 % ... | true |
95e73b7ad0a73088e67d99ce56da291d7259a439 | Ruby | KirAbrosimov/RoR-BSU-2015 | /ruby0.1.rb | UTF-8 | 278 | 3.015625 | 3 | [] | no_license | file0 = File.open('animation0.txt')
file1 = File.open('animation1.txt')
file2 = File.open('animation2.txt')
animation = []
animation[0] = file0.to_a
animation[1] = file1.to_a
animation[2] = file2.to_a
loop do
animation.each do |print|
puts print
sleep 0.2
end
end
| true |
08de5f207f176cb42086a393f3d6d6f33e10a468 | Ruby | corydissinger/political-buzz | /app/models/api_request.rb | UTF-8 | 4,488 | 2.609375 | 3 | [] | no_license | require 'json'
require 'httparty'
class ApiRequest
$urlEngine = nil
def initialize
$urlEngine = UrlEngine.new
end
def getCategoryArticleHashForStatement(statement)
$troveResults = getTroveAnalysis(statement)
$entities = $troveResults['entities']['resolved']
$categoryUrlPairs = H... | true |
8810fa8022422c287e32cd87a2d06dcd60c0df52 | Ruby | chrisadames/introduction_to_programming | /flow_control/flow_control_exercises.rb | UTF-8 | 2,739 | 4.71875 | 5 | [] | no_license | # flow_control_exercises.rb
# 1. Write down whether the following expressions return true or false. Then type the expressions into irb to see the
# results.
(32 * 4) >= 129 # false
false != !true # false
true == 4 # false
false == (847 == '847') # true
(!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false # tr... | true |
59706d47ac0b9307a065f43841c70dce9d96cdf0 | Ruby | scryptmouse/dux | /spec/support/blank_helpers.rb | UTF-8 | 1,837 | 2.640625 | 3 | [
"MIT"
] | permissive | module DuxTesting
module BlankHelpers
NOTHING = Object.new.freeze
module SpecMethods
def test_blankness_of(value: NOTHING, expectation:, description: nil, &block)
label =
if description.nil?
unless value.equal?(NOTHING)
"`#{value.inspect}`"
else
... | true |
b5aee6c78182919aa1606112d51c78333d66a3e4 | Ruby | s11rikuya/worlder | /point_calculation.rb | UTF-8 | 947 | 2.921875 | 3 | [] | no_license | module PointCalculation
require 'json'
require 'open-uri'
DISTANCE_API = 'http://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/bl2st_calc.pl?'.freeze
def distance(lat1, lng1, lat2, lng2)
req_params = {
outputType: 'json', # 出力タイプ
ellipsoid: 'bessel', # 楕円体
latitude1: lat1, # 出発... | true |
fbe84c752a85b91e04cd310c2fe15c0170b14ece | Ruby | sdmalek44/date_night | /test/binary_search_test.rb | UTF-8 | 3,037 | 3.03125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/binary_search.rb'
class BinarySearchTest < Minitest::Test
def test_if_it_exists
tree = BinarySearchTree.new
assert_instance_of BinarySearchTree, tree
end
def test_insert_and_include
tree = BinarySearchTree.new
assert_equal 0, ... | true |
6c5cd3a829c65b2b6082e2ce410314736bdcb620 | Ruby | ahopkins94/battle2 | /app.rb | UTF-8 | 579 | 2.609375 | 3 | [] | no_license | require 'sinatra'
require_relative 'lib/player'
require_relative 'lib/game'
class Battle < Sinatra::Base
enable :sessions
before do
@game = Game.instance
end
get '/' do
erb(:index)
end
post '/names' do
player_1 = Player.new(params[:player_1])
player_2 = Player.new(params[:player_2])
@game = Game.create(pl... | true |
54cc50cf64b7593f35fb4ebf89f4905cf86de3da | Ruby | drinkyouroj/domain-checker | /domain-checker.rb | UTF-8 | 727 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'whois'
input_list = ARGV.first
input_file = open(input_list)
input_file.each_line { |domain|
whois = Whois::Client.new(:timeout => 10)
record = whois.lookup(domain.downcase.chomp)
registrar_url = record.registrar.url
registrar_name = record.registrar.name
gd_url = false
gd_name = ... | true |
ec152c17966eabc60e431d3e2be54bc9206ecde8 | Ruby | YSavir/TDD-tic-tac-toe | /spec/lib/tic_tac_toe/player_spec.rb | UTF-8 | 2,030 | 2.890625 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe TicTacToe::Player, :type => :model do
describe 'When initialized' do
describe 'as a human player' do
it 'should be human' do
player = build :human_player
expect(player.human?).to be true
end
end
describe 'as a computer player' do
i... | true |
bbe145155858e9a41a0b246ca152a2f5df5cec9c | Ruby | fastmezon/reconstructor | /spec/coef_calc_spec.rb | UTF-8 | 1,393 | 2.625 | 3 | [] | no_license | require 'spec_helper'
describe CoefCalc do
let(:wkt_reader) { Geos::WktReader.new}
describe '.gen_pixel' do
let(:pixel) { wkt_reader.read('POLYGON((0.5 0.5, 1.5 0.5, 1.5 1.5, 0.5 1.5, 0.5 0.5))') }
it { expect(subject).to respond_to(:gen_pixel).with(3).arguments }
it 'return correct pixel' do
e... | true |
e63e0ff935d68d171033d2b3e87c72bc6a8bf935 | Ruby | samuelvary1/my-select-001-prework-web | /lib/my_select.rb | UTF-8 | 191 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_select(collection)
# your code here!
i = 0
selected_array = []
while collection[i]
selected_array << collection[i] if yield(collection[i])
i += 1
end
selected_array
end
| true |
605d2b49563305d581845b5b75f6c1d31f9dbd6c | Ruby | sienna-kopf/sweater_weather | /spec/services/map_quest_service_spec.rb | UTF-8 | 1,594 | 2.625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe MapQuestService do
context 'instance methods' do
context '#lat_long' do
it "takes in a location and transforms it into lat and long coordinates", :vcr do
location = "denver, co"
service = MapQuestService.new
response = service.lat_long(location)... | true |
ac015b8403d5a1aec6b2152869bc376f22eed5d9 | Ruby | tquillin/main | /db/seeds.rb | UTF-8 | 313 | 2.53125 | 3 | [] | no_license | require 'csv'
puts 'Parsing File'
data = CSV.foreach('./School_Progress_Report_2010-2011.csv', headers: true).map do |row|
{
name: row['SCHOOL'],
admin: row['PRINCIPAL'],
level: row['SCHOOL LEVEL'],
grade: row['2010-2011 OVERALL GRADE']
}
end
puts 'Placing in Database'
Score.create(data);
| true |
1352a813719f5954b1d6e783cd42f43f5db4f394 | Ruby | NancyKo/age-facts | /lib/user.rb | UTF-8 | 254 | 2.890625 | 3 | [] | no_license | require 'open-uri'
class User
attr_accessor :day, :month, :year
def initialize(month, day, year)
@day = day
@year = year
@month = month
end
def birthday_trivia
open("http://numbersapi.com/#{@month}/#{@day}").read
end
end
| true |
39585c42a2bf8405285804a33e4f02a6e41229eb | Ruby | wtartanus/Hotel | /hotel_chain.rb | UTF-8 | 642 | 2.8125 | 3 | [] | no_license | #class Hotel_chain
class Hotel_chain
#shoudl have
#name #hotels
attr_accessor :name, :hotels
def initialize(name, hotels)
@name = name
@hotels = hotels
end
#methods
#check another hotels for room avability
def check_avabality
hotel_avability = []
for hotel in @hotels
... | true |
74d6df459001ed404e21c4cf5e2803910aa66c5a | Ruby | irocho/ruby | /rubitos/factorial.rb | UTF-8 | 286 | 2.921875 | 3 | [] | no_license | ################################
#
# openHPI
# Factorial dun número
#
# executar en vim como :!ruby %
# executar no terminal como ruby factorial.rb
# en Sublime Text con mazá B
#
###############################
#
def factorial(n)
n==0?1:n*factorial(n-1)
end
puts factorial(5)
| true |
e24ed96c90e6e39f041a6e95f0d7b2fea63cb9d4 | Ruby | nvenky/splay | /app/models/scenario.rb | UTF-8 | 1,382 | 2.96875 | 3 | [] | no_license | class Scenario
attr_accessor :side, :range, :market_type, :min_odds, :max_odds
def initialize(*h)
if h.length == 1 && h.first.kind_of?(Hash)
h.first.each { |k,v| send("#{k}=",v) }
end
end
def back?
@side == 'BACK'
end
def lay?
@side == 'LAY'
end
def lay_sp?
@side == 'LAY (S... | true |
446e8c74d9f1c604e98b75a9553a23793106b3f6 | Ruby | mbrand12/t10 | /test/unit/thesaurus_test.rb | UTF-8 | 796 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class ThesaurusTest < Minitest::Test
def setup
@thesaurus = T10::Thesaurus
@sample_verbs = {
go: %i(go walk move),
look: %i(look stare glare fixate)
}
@sample_nouns = {
cat: %i(cat kitty tabby),
dragon: %i(dragon)
}
@sample_modifiers = {
}
... | true |
feedec8c979b4e53b07ee3931fe3ebf3c114d994 | Ruby | andrzejsliwa/cqrs-es-twitter-app | /lib/read_model/user.rb | UTF-8 | 392 | 2.546875 | 3 | [] | no_license | module ReadModel
class User
def initialize(redis)
@redis = redis
end
def handle_event(event)
case event
when Events::UserSignedUp
redis.hset("user:#{event.user_id}", :username, event.auth_info.username)
redis.hset("user:#{event.user_id}", :full_name, event.auth_info.ful... | true |
631975e51ec302ed4a29ded9af3596709546df28 | Ruby | aiywatch/Robot-mock-test | /lib/battery.rb | UTF-8 | 182 | 2.84375 | 3 | [] | no_license | require_relative 'item'
class Battery < Item
NAME = 'Battery'
WEIGHT = 25
def initialize
super(NAME, WEIGHT)
end
def recharge(robot)
robot.recharged()
end
end | true |
58ff97ae3886c4444492b635d20b13986b75751a | Ruby | drbrain/AOC | /2018/02b.rb | UTF-8 | 938 | 3.328125 | 3 | [] | no_license | require_relative "../aoc"
test <<-INPUT, "fgij"
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
INPUT
##
# This implementation uses +catch+ and +throw+ to break out of nested blocks.
# Using +return+ requires a method. Extracting a method seemed like more work
# than indenting the code one level and wrapping it in +catch+... | true |
c8eb020adc2aa373e3ab2becb7c6fdcd5beaef9f | Ruby | davidqin/Note_archive | /ruby/fiber/producer_and_consumer.rb | UTF-8 | 365 | 3.203125 | 3 | [] | no_license | # coding: utf-8
require 'fiber'
def send(x)
Fiber.yield x
end
def receiver producer
producer.transfer
end
def producer
Fiber.new do
while true
x = gets.chomp
send(x)
end
end
end
def consumer(producer)
while true
x = receiver(producer)
break if x == 'quit'
puts x
end
end
... | true |
41a1b1616ced067eca1565f0625333515c08728e | Ruby | Suraj-Surendran/Fizz-Buzz | /main.rb | UTF-8 | 152 | 3.734375 | 4 | [] | no_license | #Fizz Buzz
for i in 1..100
if i%3==0 && i%5==0
puts "Fizz Buzz"
elsif i%3==0
puts "Fizz"
elsif i%5==0
puts "Buzz"
else
puts "#{i}"
end
end | true |
ff0070db767297792c1c0868802ef0ac2a5552b6 | Ruby | schadenfred/handsome_fencer-crypto | /lib/handsome_fencer/crypto.rb | UTF-8 | 2,241 | 2.796875 | 3 | [
"MIT"
] | permissive |
require "handsome_fencer/crypto/version"
require "openssl"
require "base64"
module HandsomeFencer::Crypto
class << self
def generate_key
@cipher = OpenSSL::Cipher.new 'AES-128-CBC'
@salt = '8 octets'
@new_key = @cipher.random_key
Base64.encode64(@new_key)
end
def write_to_file(... | true |
b14f5c794bcb0c0da36cb518aa401003c092c770 | Ruby | kivanio/brcobranca | /lib/brcobranca/boleto/credisis.rb | UTF-8 | 4,462 | 3.015625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | # frozen_string_literal: true
module Brcobranca
module Boleto
# CrediSIS
class Credisis < Base
validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.'
validates_length_of :conta_corrente, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.'
validates... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.