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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cd56ec6816bf1c6dc38425dc04b5fe28786f7569 | Ruby | spam-elgoog/ruby-samples | /algorithms/primes.rb | UTF-8 | 3,492 | 3.53125 | 4 | [] | no_license | require 'openssl'
def is_prime_simple(n)
if n <= 1
return false
elsif n <= 3
return true
elsif n % 2 == 0 || n % 3 == 0
return false
end
i = 5
while i * i <= n
if n % i == 0 || n % (i + 2) == 0
return false
end
i += 6
end
return true
end
# complex
def is_prime(n)
if n... | true |
61d1d2677cfd49cbe703451c1c631d52de8ea4d6 | Ruby | BohanHsu/leetcode2 | /test/patching_array_test.rb | UTF-8 | 1,390 | 2.625 | 3 | [] | no_license | require 'minitest/autorun'
require '../patching_array'
describe 'min_patches(nums, n)' do
it 'should work1' do
nums = [1,5,10]
n = 20
expected_result = 2
min_patches(nums, n).must_equal(expected_result)
nums = [1,3]
n = 6
expected_result = 1
min_patches(nums, n).must_equal(expected_r... | true |
7385296cdb8b39c3dc06b862060e2be6028c6cdc | Ruby | MendyCohen/advanced-hashes-hashketball-dumbo-web-100818 | /hashketball.rb | UTF-8 | 7,143 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def game_hash
{
home: {
team_name: "Brooklyn Nets",
colors: ["Black", "White"],
players: {
"Alan Anderson" => {
number: 0,
shoe: 16,
points: 22,
rebounds: 12,
assists: 12,
steals: 3,
blocks: 1,
slam_dunks: 1
... | true |
f01f314c15584cab8a91bd02d411908876d84376 | Ruby | scarlettperry/badges-and-schedules-prework | /conference_badges.rb | UTF-8 | 649 | 3.921875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def badge_maker (name)
"Hello, my name is #{name}."
end
def batch_badge_creator (attendees)
badges = []
attendees.each do |name|
badges.push("Hello, my name is #{name}.")
end
badges
end
def assign_rooms (attendees)
room_assignments = []
room = 1
attendees.each do |name|
... | true |
a7aa05e8f830ecf8308aed45ea7e26f85029b767 | Ruby | caalberts/algorithmic-toolbox | /week3/party.rb | UTF-8 | 260 | 3.59375 | 4 | [] | no_license | def group_children(children)
i = 0
group_count = 0
while i < children.size
age = children[i]
max_age = age + 1
group_count += 1
i += 1
while i < children.size && children[i] <= max_age
i += 1
end
end
group_count
end
| true |
424c25a2f9572fd7c2d86ce86aaa1e90708a12cd | Ruby | tstaros23/mastermind | /lib/game.rb | UTF-8 | 4,493 | 3.53125 | 4 | [] | no_license | require './lib/statement'
require './lib/player_input'
require './lib/compare_color_position'
require './lib/winning_combo'
class Game
def initialize
@statement = Statement.new
@guesses = 0
end
#game.new makes Statement.new available in the game class
def main_menu_interaction
mastermind_intro
... | true |
bc66291c10e7f35f4b39c95b3e6b95ed902f0b6c | Ruby | learn-co-students/chicago-web-051319 | /19 - Rails Forms and REST/app/models/textbook.rb | UTF-8 | 440 | 2.59375 | 3 | [] | no_license | class Textbook < ApplicationRecord
has_many :rentals
has_many :students, through: :rentals
validates :vandalized, inclusion: { in: [true, false],
message: "%{value} is not valid, please select true or false" }
validate :title_starts_with_word_the
def title_starts_with_word_the
if title.downcase[0..3... | true |
6fb382698790dd0debdd7bb377e9ad116ae4dd87 | Ruby | OhCoder/designpatterns-ruby | /proxy/giveGift.rb | UTF-8 | 226 | 2.8125 | 3 | [
"MIT"
] | permissive | class GiveGift
def giveFlower
puts "someone gives flower to somebody"
end
def giveDoll
puts "someone gives doll to somebody"
end
def giveChocolate
puts "someone gives chocolate to somebody"
end
end
| true |
b326ac5d9281bbdfb9f879739d488a3423971bed | Ruby | manoj-k-r/odin_webdev | /ruby_programs/Hangman/hangman.rb | UTF-8 | 4,885 | 3.484375 | 3 | [] | no_license | require 'csv'
require 'json'
class Game
def initialize(word='',dash_arr=[],rem_letters=[],wrong_guess=0,loaded=false)
@@alpha_arr=Array.new
for i in 97..122
@@alpha_arr.push(i.chr)
end
if loaded==false
puts "Welcome to a game of Hangman. Do you want to load an... | true |
478fee74cf06897ca52cc20a868ffc002b7e4f57 | Ruby | chazu/magister_poc | /lib/helpers.rb | UTF-8 | 3,279 | 3.125 | 3 | [] | no_license | require 'heist'
module Magister
module Helpers
def context_array_to_index_key(context_array)
"/" + context_array.join("/")
end
def index_key_to_context_array(index_key)
res = index_key == "/" ? [] : index_key.split("/")
if res.length > 0
res.shift
end
res
end
... | true |
f2595e8a686117425f297f7db86b1c9430a7e4f9 | Ruby | maximgladkov/mobile_stores | /spec/app_spec.rb | UTF-8 | 1,674 | 2.75 | 3 | [
"MIT"
] | permissive | require "spec_helper"
module MobileStores
describe "App" do
describe "#in" do
it "should accept symbol as argument" do
stores = {
app_store: AppStore,
google_play: GooglePlay,
windows_store: WindowsStore,
blackberry_world: BlackBerryWorld,
amaz... | true |
a0930b0e56edfee56326288aabdf5c11419c01b3 | Ruby | codigonet/E6CP1A1 | /2 ciclos/ejercicio6.rb | UTF-8 | 220 | 3.703125 | 4 | [] | no_license | # El siguiente ejercicio busca calcular el factorial de 10.
# TIP: El resultado es 3628800.
multiplicacion = 1
# 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
10.times do |i|
multiplicacion *= i + 1
end
puts multiplicacion
| true |
6ae0101e1f6a45f5480da371c7f1311ee9cbe9d2 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/filtered-submissions/4f842a315b5541369cbd1aa21ab3932b.rb | UTF-8 | 294 | 3.453125 | 3 | [] | no_license | def compute(s1, s2)
s1_chars = s1.chars
s2_chars = s2.chars
hamming = 0
len = s1_chars.length > s2_chars.length ? s2_chars.length : s1_chars.length
len -= 1
for i in 0..len
if s1_chars[i] != s2_chars[i]
hamming += 1
end
end
hamming
end | true |
07734f02dbc3b07f2990b3a1ad7031032f4a7dd6 | Ruby | 64kramsystem/competitive-programmer-core-skills-progress-incomplete | /week_1_programming_competitions/addsub.rb | UTF-8 | 725 | 3.640625 | 4 | [
"Unlicense"
] | permissive | #!/usr/bin/env ruby
def main(input, output)
x, y, z = input.readline.split(' ').map(&:to_i)
last_val = 0
# The series has two possible values (for i >= 1):
#
# - nx - (n - 1)y
# - nx - ny
#
# With i reaching large values, e.g. 10000, even with the minimum difference between x and y (-> 1),
# e.g. x... | true |
a9fa35d5c432bc4fffa9c7ccca50eeaa19c557eb | Ruby | chriscarter90/train-rec | /bin/autotag | UTF-8 | 951 | 3.078125 | 3 | [] | no_license | #!/usr/bin/env ruby
class Tag
def initialize(tag_string)
@tag_string = tag_string
@tag_numbers = @tag_string.split('.').map(&:to_i)
end
def major
@tag_numbers[0]
end
def minor
@tag_numbers[1]
end
def patch
@tag_numbers[2]
end
def numbers
@tag_numbers
end
def <=>(oth... | true |
6826639cc4706c5c92782531d127e26f8d6a0f08 | Ruby | levidsmith/timelapsemaker | /dup.rb | UTF-8 | 695 | 3.140625 | 3 | [] | no_license | # Timelapse Maker
# 2015 Levi D. Smith
# Web: levidsmith.com
# Twitter: @GaTechGrad
# This file duplicates an image in a directory
# the specified number of times
# This is useful for displaying a static image
# such as a title over a number of seconds in
# a time lapse
require 'fileutils'
OUT_DIR = "out"
# The im... | true |
f603b06f182996e809f18262db7b3cfb26a90397 | Ruby | edshadi/design_patterns_in_ruby | /behavioral/observer2.rb | UTF-8 | 1,986 | 4.09375 | 4 | [] | no_license | # observer2.rb
# Slight modification of previous example with metaprogramming to wrap methods
# that needs to be observed.
# 1. observer
class Observer
def initialize(name)
@name = name
end
def update(value)
puts "updated " + @name + ". New value: " + value
end
end
# 2. Observable, serves as a co... | true |
5f51493fcb0622606c24a571b64e6152c0eb9289 | Ruby | sanchojaf/travel_data_center | /db/load_data/load_data.rb | UTF-8 | 572 | 2.75 | 3 | [] | no_license | #!/usr/bin/ruby
path = "#{Rails.root}/db/load_data/hotels.xls"
puts path
book = Spreadsheet.open path
book.worksheets
sheet = book.worksheet 0
for row in 6..sheet.last_row_index
if sheet[row,0]
destination = sheet[row,0]
chain = sheet[row,1]
hotel_name = HotelName.create({:name => sheet[row,2]})
... | true |
b8201a4da593bf377febb88cdb329801666e633e | Ruby | inanecuteposse2/wizard_bank | /lib/bank.rb | UTF-8 | 588 | 3.65625 | 4 | [] | no_license | require_relative "person"
class Bank < Person
attr_reader :name
def initialize(name)
@name = name
end
def open_an_account(person)
bank_name = @name
person.accounts[bank_name] = 0
"An account has been opened for #{person.name} with #{bank_name}."
end
d... | true |
096d71517b7c86b665db52960e630e4fc9c33b4c | Ruby | saintaze/Micro-Reddit | /app/models/user.rb | UTF-8 | 765 | 2.5625 | 3 | [] | no_license | class User < ApplicationRecord
# user has many posts and comments association
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
#hooks
before_save :downcase_fields
#email regex for valid email
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
#username validation
v... | true |
c750b039c75d7623230481dc2447d5918e18f0ca | Ruby | RobinSanta/Rails-Practice-Code-Challenge-Travelatr | /app/models/blogger.rb | UTF-8 | 417 | 2.640625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Blogger < ApplicationRecord
has_many :posts
has_many :destinations, through: :posts
validates :name, uniqueness: true
validates :age, numericality: {greater_than: 0}
validates :bio, length: {minimum: 30}
def total_likes
all_posts = self.posts
post_map = all_posts.map do |post|
post.likes
end
po... | true |
5a09e0a3f4775e64a36544d17b249cca68c94b38 | Ruby | TomKirby/renalware-core | /app/controllers/renalware/patients/primary_care_physician_controller.rb | UTF-8 | 3,169 | 2.65625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_dependency "renalware/patients"
# Note this singular resource is for updating the patient.primary_care_physician.
# The plural resource in the same folder is for managing primary_care_physicians.
module Renalware
module Patients
class PrimaryCarePhysicianController < BaseCo... | true |
b28c8f45b2a5440d721af73d0f7a4c467bf0c605 | Ruby | mattenbar/oo-basics-onl01-seng-pt-032320 | /lib/book.rb | UTF-8 | 359 | 3.890625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # create new class called Book
class Book
#initializes with a title
def initialize (title)
@title = title
end
#writes the getter and setter for our methods
attr_accessor :title, :author, :page_count, :genre
#turn page method has its own output so we write it seperate
def turn_page
puts "Flipping the ... | true |
28ffa43f2c323d270cdfbe8e54c54940688e998b | Ruby | JennicaStiehl/sweater-weather | /spec/models/weather_creator_spec.rb | UTF-8 | 917 | 2.671875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe WeatherCreator, type: :model do
describe 'class methods' do
it 'can get attributes' do
attributes = Location.new(city: "denver,co",
latitude: "39.7392358",
longitude: "-104.9... | true |
991d097a87f9565440bd48479c3d002fee767bee | Ruby | 1000Memories/interpreted-date | /spec/interpreted_date_spec.rb | UTF-8 | 6,116 | 3.09375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe InterpretedDate do
describe "with no date attributes" do
subject { InterpretedDate.new }
it "returns nil string" do
subject.to_s.should be_nil
end
it "returns nil integer" do
subject.to_i.should be_nil
end
end
describe "with decade only" do
s... | true |
c8c77fcd9ab80029439b1ffebf347b3b417062d1 | Ruby | filiptepper/webclusters-redis | /benchmark-redis-mget.rb | UTF-8 | 298 | 2.59375 | 3 | [] | no_license | $redis.flushall
puts "[redis] set"
puts Benchmark.measure {
1.upto ITERATIONS do |i|
$redis.set "an-average-key-#{i}", "an-average-value-#{i}"
end
}
keys = []
1.upto ITERATIONS do |i|
keys << "an-average-key-#{i}"
end
puts "[redis] mget"
puts Benchmark.measure {
$redis.mget keys
}
| true |
844440c58866c27a4d938a0cc7c6a11b891995e8 | Ruby | JessAntunes/randomTTT | /app/models/game.rb | UTF-8 | 2,835 | 3.578125 | 4 | [] | no_license | class Game < ApplicationRecord
WIN_COMBINATIONS = [0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[6,4,2]
# x goe... | true |
66ecd435ac8570a1f62f76215fa37c20309e2b2c | Ruby | ericwhited/Basic-Ruby | /rubyBasics.rb | UTF-8 | 793 | 4.21875 | 4 | [] | no_license | # # Add a function that takes a string as an argument and adds only in america at the end
# def OIA(str)
# str + ' ' + 'Only in America!'
# end
# OIA('Eric')
#find the max value in an array of numbers
def max(arr)
puts arr.sort[-1]
end
max([1,20,2000,10,200,100])
# # Arrays and Hashes
# def myFunc(arr1... | true |
e71ab410738fb6e7116c8ed32760b1da8b84f49d | Ruby | TIY-DC-ROR-2015-Jan/course-notes | /jan/29/pig.rb | UTF-8 | 953 | 4.125 | 4 | [] | no_license | # TODO: Track player names?
current_player = 1
max_score = 10
p1_score = 0
p2_score = 0
def take_turn
turn_total = 0
loop do
roll = rand(1..6)
puts "You rolled a #{roll}."
if roll == 1
puts "Bad news :("
return 0
else
turn_total += roll
puts "Roll again (turn total so fa... | true |
f4cf9129f4a15869bf8e36019b4410d4451f7df8 | Ruby | kzielonka/ddd_events_app | /events/lib/events/value_objects/title.rb | UTF-8 | 666 | 2.734375 | 3 | [] | no_license | # frozen_string_literal: true
class Events
module ValueObjects
class Title
def initialize(title)
@title = if title == :not_set
:not_set
else
String(title).strip.freeze
end
end
def to_s
set? ? @title : ''
... | true |
a02f7b578c06b79ee0a9cfc30622b628b413dc88 | Ruby | lakaniemi/wadror | /spec/models/user_spec.rb | UTF-8 | 4,645 | 2.6875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
it "has the username set correctly" do
user = User.new username:"Pekka"
expect(user.username).to eq("Pekka")
end
it "is not saved without a password" do
user = User.create username:"Pekka"
expect(user).not_to be_valid
expect(User.count).to ... | true |
b74ac84cfb84133de8b7e63d919009bc2132b78b | Ruby | clairebvs/sweater-weather | /app/models/forecast.rb | UTF-8 | 920 | 3.03125 | 3 | [] | no_license | class Forecast
def initialize(location)
@location = location
end
def current_weather
@current_weather ||= dark_sky_service.weather_forecast[:currently]
end
def hourly_weather
@hourly_weather ||= dark_sky_service.weather_forecast[:hourly][:data]
end
def daily_weather
@daily_weather ||= d... | true |
7f7e924cdf510c367f02ca75da2153ad3a7b9c95 | Ruby | itorterat/CodeWars | /8_kyu/string_repeat/string_repeat.rb | UTF-8 | 132 | 3.078125 | 3 | [] | no_license | # URL:
# https://www.codewars.com/kata/57a0e5c372292dd76d000d7e
#
# Title:
# String repeat
#
# v1
def repeat_str(n, s)
s * n
end
| true |
bd16b07fd4b4c3aac838fcca1cfe9787dd83861e | Ruby | lucasjct/Ruby-Brief-Introdution | /POO/exemplos/classe2.rb | UTF-8 | 245 | 3.203125 | 3 | [] | no_license | #Overrinding (Sobrescrever)
class ClasseMae
def correr
puts "A mãe corre!"
end
end
class ClasseFilha < ClasseMae
def correr
puts super
puts "cansei"
end
end
objeto = ClasseFilha.new
objeto.correr
| true |
6321bffee23b797b083ca22600ebaa83e0c67a54 | Ruby | VXhelilaj/ObjectOrientedProgramming | /mars_rover.rb | UTF-8 | 1,452 | 4.21875 | 4 | [] | no_license | class Rover
# In order to control a rover, NASA sends a simple string of letters. The possible letters are 'L', 'R' and 'M'.
# 'L' and 'R' makes the rover spin 90 degrees left or right respectively,
# without moving from its current spot.
# 'M' means move forward one grid point, and maintain the same heading.
def ... | true |
389b51c305f0dadecf05405ed18d85b58cb85328 | Ruby | kwongius/FabricPPod | /updateKits.rb | UTF-8 | 3,165 | 2.59375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# Copyright (c) 2015 Kevin Wong <snarpel@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | true |
c688b36eeaffc3176c7919437e6b99ffa94a74d7 | Ruby | adrianpearman/ruby_assignment2 | /exercise8.rb | UTF-8 | 139 | 2.9375 | 3 | [] | no_license | expenses = [250, 7.95, 30.95, 16.50]
total = expenses.reduce (:+)
#expenses.inject(0){|sum,x| sum + x }
puts "Total expense is $#{total}"
| true |
1c954b401d0a62477fe1eb770c304c0811e8dfd6 | Ruby | luizrogeriocn/ruby_rentacar | /Location.rb | UTF-8 | 224 | 3.265625 | 3 | [] | no_license | class Location
attr_accessor :client, :vehicle, :duration
def initialize(client, vehicle, duration)
@client = client
@vehicle = vehicle
@duration = duration
end
def add_duration(days)
@duration += days
end
end | true |
3bc730988d3aa7011abcf6078e808509be1fb830 | Ruby | run-after/chess | /spec/queen_spec.rb | UTF-8 | 4,226 | 3.4375 | 3 | [] | no_license | require_relative "../lib/game.rb"
RSpec.describe Queen do
describe "#team" do
it "gives the corresponding color" do
queen = WhiteQueen.new("e4")
expect(queen.team).to eql("white")
queen = BlackQueen.new("e4")
expect(queen.team).to eql("black")
end
end
describe "#show" do
it "... | true |
4e28d11b26719614f175cbd6a6c132590ff3ce1e | Ruby | johnnyt/geocell | /lib/geocell/cell.rb | UTF-8 | 759 | 2.78125 | 3 | [
"MIT"
] | permissive | module Geocell
class Cell
attr_reader :char, :parent, :kids
# See ruby_engines/#{RUBY_ENGINE}.rb
def self.initialize_store; end
def self.root; end
def self.[](hash_string)
root[hash_string]
end
def initialize(parent=nil, char='')
@parent, @char = parent, char
end
de... | true |
586fdbffa8e5861befa1e73bc90d54c39b3b7e1b | Ruby | cold-pumpkin/Math-Puzzle | /Solution/q50_01.rb | UTF-8 | 853 | 3.375 | 3 | [] | no_license | N = 8 # 모래시계의 수
GOAL = [1] * N # 모두 1이 되면 다음에 동시에 아래로 떨어진다
count = 0
(1..N).to_a.permutation{|init| # 초기 상태를 순열로 설정
hourglass = init
pos = 0
log = {} # 같은 상태가 되는지를 체크하는 로그
while log[hourglass] != pos # 과거에 같은 상태가 있다면 종료
if hourglass == GOAL then # 목표 형에 달하면 종료
count += 1
break
... | true |
e42cc10abeaaeed1ea81e594aec0f4ce0aa8a14d | Ruby | JoshuaMcEvoy/WDi24-Homework | /madeleine_milasas/week_05/day_01/games/app/controllers/number_controller.rb | UTF-8 | 517 | 2.640625 | 3 | [] | no_license | class NumberController < ApplicationController
def generate
session[:number] = Random.rand(1..10)
end
def play
@numbers = (1..10).to_a
end
def result
@correct = false
if params[:id].to_i != session[:number]
messages = ["Nup", "Not that one", "No way", "Nope", "Kinda, but, no. No defini... | true |
328271dedcb7f32fb451417f2a03b6f9573cc569 | Ruby | nog/atcoder | /contests/arc120/a/main.rb | UTF-8 | 236 | 2.625 | 3 | [] | no_license | N = gets.to_i
A = gets.split.map(&:to_i)
sum = 0
sumsum = 0
max = 0
N.times do |k|
a = A[k]
max = a if a > max
sum += a
warn "max:#{max} sum:#{sum} a:#{a}"
puts ( sum + (max * (k+1)) + sumsum)
sumsum += sum
end | true |
dd973025e437930207273d6968006a60cd7e67a4 | Ruby | AkuaAA/array-CRUD-lab-ruby-apply-000 | /lib/array_crud.rb | UTF-8 | 550 | 3.609375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def create_an_empty_array
my_array = []
end
def create_an_array
my_array = ["Monday","Tuesday","Wednesday","Thurday"]
end
def add_element_to_end_of_array(array,arrays)
array<< "arrays!"
end
def add_element_to_start_of_array(array,wow)
array.unshift "wow"
end
def remove_element_from_end_of_array(wow)
wow.pop
end
... | true |
6a8a08031256a24b9cac4a6e92c82ed31a5cccd4 | Ruby | didiermarques/exruby | /exo_06.rb | UTF-8 | 632 | 3.25 | 3 | [] | no_license | number_of_hours_worked_per_day = 10
number_of_days_worked_per_week = 5
number_of_weeks_in_THP = 11
puts "Travail : #{number_of_hours_worked_per_day * number_of_days_worked_per_week * number_of_weeks_in_THP}"
puts "Et en minutes ça fait : #{number_of_minutes_in_an_hour * number_of_hours_worked_per_day * number_of_days... | true |
b4eae072f8f412b05cffe1b2ffdd17f1b36d9a85 | Ruby | kristing81/Mox | /app/models/concerns/fake_product.rb | UTF-8 | 345 | 2.75 | 3 | [] | no_license | class FakeProduct
attr_reader :name, :price, :department
def initialize
@name = Faker::Commerce.product_name
@title = Faker::Commerce.price
@company = Faker::Commerce.department
end
def FakeProduct.fake(count = 1)
products = []
count.times do
products << FakeProduct.new
end
... | true |
d7886240a1dbaf6fe18ca714662a89f391c877e7 | Ruby | rondale-sc/generate_pry_man | /generate_pry_man.rb | UTF-8 | 1,781 | 2.703125 | 3 | [] | no_license | class GeneratePryMan
require 'ronn'
require 'pry'
require 'erb'
def initialize(opts={})
@basename = opts.fetch(:basename, "./templates/pry.1")
@html_template = ERB.new(File.read(@basename + ".erb"), 0, "%<>")
@man_sections = opts.fetch(:man_sections, get_man_sections)
@ronn_file_obj = opts.fet... | true |
db6a3eda35299df08c1098c89c2232c5895ca5c8 | Ruby | benja2208/learn_to_program | /ch13-creating-new-classes/extend_built_in_classes.rb | UTF-8 | 207 | 4.03125 | 4 | [] | no_license | class Integer
def factorial
num = self
if num < 0
return 'You can\'t take the factorial of a negative number!'
elsif num <= 1
1
else
num * (num-1).factorial
end
end
end
puts 10.factorial | true |
f76a6a1b750c99638140b3198474ecce2332e95f | Ruby | Kole565/RubyRush | /programms/internet_tools/currency/scripts/show_single.rb | UTF-8 | 1,377 | 2.765625 | 3 | [] | no_license | require "optparse"
require_relative "../lib/showsingle.rb"
options = {}
OptionParser.new do | opts |
# If use like script - get options and call show_single
opts.banner = "Usage show_single script"
opts.on("-h", "--help", "Print help") do
puts opts
exit
end
opts.on("-o", "--open_curr OPEN_CURR", String, "... | true |
2a55653f5f7f7bebd573540e6355391407baa5ec | Ruby | paulas/crypto_gost | /lib/crypto_gost/create.rb | UTF-8 | 1,323 | 2.75 | 3 | [
"MIT"
] | permissive | module CryptoGost
# DigitalSignature
#
# @author WildDima
class Create
attr_reader :group, :public_key, :signature_adapter, :create_hash
def initialize(message, group, signature_adapter: Signature,
create_hash: Stribog::CreateHash)
@signature_adapter = signature... | true |
46d1e5e0171274db877380643d7231538a122155 | Ruby | sasikalaj/rubyprogramming | /Basefolder/modules_and_classes/class_extends_modules.rb | UTF-8 | 1,910 | 4.1875 | 4 | [] | no_license | # The astute reader might point out that classes are actually objects in Ruby.
# Let’s see what happens when we use extend in a class definition:
# What exactly are we extending here? Within the class definition,
# extend is being called on the Human class itself;
# we could have also written self.extend(SuperPowers).... | true |
2aeb504fd7125ab74014d6872d67ef3b80a55e52 | Ruby | BOISSARD/TPs-Ruby | /TP1/bin.rb | UTF-8 | 566 | 2.984375 | 3 | [] | no_license | require_relative 'creature'
require_relative 'gobelin'
require_relative 'compagnie'
require_relative 'troll'
require_relative 'fabrique'
comp = Compagnie.new
puts comp.compagnie
grok = Troll.new("Grok",24)
gruk = Troll.new("Gruk",27)
zak = Gobelin.new("Zak",12)
zog = Gobelin.new("Zog",13)
comp.ajout gruk
comp.ajout... | true |
47619c18b8716cf34e2fe12f8058e8463f5c3d5b | Ruby | benrodenhaeuser/LS_101 | /lesson_05/example03.rb | UTF-8 | 1,315 | 4.03125 | 4 | [] | no_license | [[1, 2], [3, 4]].map do |arr|
puts arr.first
arr.first
end
# What will be printed?
1
3
# What will be returned?
# => [1, 3]
# What are the relevant actions to distinguish?
# 1. method call map
# 2. block execution
# 3. call to first on line 3
# 4. call to puts on line 3
# 5. call to first on line 4
# By actio... | true |
e6ec1a5c415ab9423efd193373de2b8b8ba98163 | Ruby | rvachon1/rb101 | /exercises/easy4/integer_to_string.rb | UTF-8 | 738 | 3.75 | 4 | [] | no_license | DIGITS = {
0 => '0',
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
}
def integer_to_string(int)
str_array = []
return "0" if int == 0
while int > 0
int, digit = int.divmod(10)
str_array.unshift(DIGITS[digit])
end
str_array.join('')
end
de... | true |
7504599187b5663e3f0c09a54e5118774f001679 | Ruby | bcsaxon/ruby-enumerables-reverse-each-word-lab-dumbo-web-82619 | /reverse_each_word.rb | UTF-8 | 147 | 3.34375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(string)
string_array = string.split " "
reverse_string = string_array.collect{ |word|
word.reverse
}.join(" ")
end
| true |
dec003b2ed5e35915af3bc7ddde8bf709f054df9 | Ruby | mohammadali-bacha/Jour8_Semaine2 | /Learning/test_draft.rb | UTF-8 | 885 | 2.703125 | 3 | [] | no_license | require 'rubygems'
require 'nokogiri'
require 'open-uri'
page = Nokogiri::HTML(open('http://www.penser-entrepreunariat.fr/?page_id=120'))
page.css('#post-120 > ul').each do |el|
puts el.text,
end
=begin
class RedditScraper
def initialize
@headline = []
@agent = Mechanize.new
end
def fetch_re... | true |
4611aff23f1a0478a9d32489189b24ea098e4dce | Ruby | blacksails/kerio_monitor | /settings.rb | UTF-8 | 1,115 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'psych'
require 'io/console'
module Settings
extend self
@settings = {}
def create!
puts 'It appears that we lack a configuration file, lets create one now!'
printf 'Enter kerio host address: '
kerio_host = gets.chomp
printf 'Enter kerio port: '
kerio_port = gets.chomp
printf '... | true |
6c3ecc833bc5b4f16332704243edb6212907fc10 | Ruby | mayankja/backend-challenge | /level1/export.rb | UTF-8 | 601 | 2.53125 | 3 | [] | no_license | module Export
module ClassMethods
def export_file(json, export_path)
File.open(export_path,"w") {|f| f.write(json) }
end
def export_json_data
{ root_key => all.collect { |obj| obj.export_data }}.to_json
end
def root_key
nil
end
def export_fields
[]
end
d... | true |
61440f768a64a270add1d9accfb1c7003d505eff | Ruby | evserykh/toy_robot | /lib/command/move.rb | UTF-8 | 497 | 2.75 | 3 | [] | no_license | require File.expand_path('../movement', __dir__)
require File.expand_path('base', __dir__)
module Command
class Move < Base
private
def table
robot.table
end
def movement
@movement ||= Movement.new(row: robot.row, column: robot.column, direction: robot.direction)
end
def action... | true |
b7018115ba6f7dd7149a36f1452fe07820143a3e | Ruby | Ralej86/aA-Homeworks | /W1D5-b/map.rb | UTF-8 | 753 | 4.0625 | 4 | [] | no_license | class Map
def initialize
@map = []
end
def assign(key, value) #assigns a unique key, value pair to the map
@map.include?([key, value]) ? nil : @map << [key, value]
end
def lookup(key)
@map.select {|arr| arr[0] == key}
end
def remove(key)
@map.reject {|arr| arr[0] == key}
end
def sh... | true |
91578a930a6aa4f395dc6253d1d7da710f38a6fc | Ruby | scorrea83/sinatra-logging-in-and-out-v-000 | /app/helpers/helpers.rb | UTF-8 | 536 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Helpers
def self.current_user(session)
User.find_by(id: session[:user_id])
end
def self.is_logged_in?(session)
self.current_user(session).id == session[:user_id]
### ALTERNATIVE SOLUTION ###
# !!session[:user_id]
# => if user is logged out, session hash is empty,
# => !session[:use... | true |
bc80a17a43f00467518ac02de2e0cd0346012fb4 | Ruby | willianantunes/ruby-playground | /chapter_13/fourth_techniques.rb | UTF-8 | 1,886 | 4.3125 | 4 | [] | no_license | # 1. The most common category of changes to built-in Ruby classes is the ADDITIVE CHANGE:
# adding a method that doesn’t exist. Sample project: Active Support
# 2. A PASS-THROUGH method change involves overriding an existing method in such a way
# that the original version of the method ends up getting called along wi... | true |
71fa1cbb7d0dd764425c953017724e4623371ad3 | Ruby | kenchan/competitive_programming | /atcoder/abc133/b.rb | UTF-8 | 214 | 2.8125 | 3 | [] | no_license | N, D = gets.split.map(&:to_i)
X = N.times.map {
gets.split.map(&:to_i)
}
puts X.combination(2).select {|x, y|
d = Math.sqrt(D.times.inject(0) {|acc, i|
acc + (x[i] - y[i]) ** 2
})
d == d.to_i
}.size
| true |
99fdb3141d4852bdc97a38e7cb881fc611a2dc62 | Ruby | locoframework/loco-rails | /test/loco/ws_connection_storage_test.rb | UTF-8 | 3,642 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'test_helper'
module Loco
class WsConnectionStorageTest < TC
before do
@storage = WsConnectionStorage.current
@storage.set('foo', 'bar')
@raw = @storage.storage
end
describe '#get' do
it do
assert_equal 'bar', @storage.get('foo')
... | true |
cd621d0d3530d2a3d0b85cd4c6753ba7c5ee9693 | Ruby | skim09/SWE_Team_Links | /features/step_definitions/link_steps.rb | UTF-8 | 1,029 | 2.625 | 3 | [] | no_license | require "rack_session_access/capybara"
Given /the following links exist/ do |links_table|
links_table.hashes.each do |link|
Link.create(link)
end
end
Given (/the following users exist/) do |users_table|
users_table.hashes.each do |user|
# each returned element will be a hash whose key is the table header... | true |
44d0336d2607eb1970138c069237fa9184ab010a | Ruby | awesome/music-transcription | /lib/music-transcription/pitch.rb | UTF-8 | 9,039 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Music
module Transcription
# Abstraction of a musical pitch. Contains values for octave, semitone,
# and cent. These values are useful because they allow simple mapping to
# both the abstract (musical scales) and concrete (audio data).
#
# Fundamentally, pitch can be considered a ratio to some base number.
# ... | true |
ad23832cc09f4bf469a34b244614d072db086fd8 | Ruby | blacknj/BasicRuby | /while.rb | UTF-8 | 642 | 4.375 | 4 | [] | no_license | #while comparison
# statements
#end
#count is the Loop Control Variable
#while (count <= 5) /// count += 1 (increments by 1) <--- These are the while statements
#////
#count = 1
#while (count <= 5)
# puts("dlroW ,olleH")
# count += 1
#end
#////
sum = 0
number = 1
while number <= 10
sum += number
number += 1
... | true |
5b1e56a6cb56e06cf5b5efc39f101f51d9e3e65e | Ruby | beacoder/depot | /app/models/user.rb | UTF-8 | 726 | 2.578125 | 3 | [] | no_license | class User < ApplicationRecord
# [117] update: rollback deletion if last user has been deleted
# declare ensure_an_admin_remains() to be called after the "SQL delete" executed
# last user deleted => exception raised => transaction rolled back
after_destroy :ensure_an_admin_remains
# [95] update: add validat... | true |
79161e5fb0096400d0cab0761afd3817a273898a | Ruby | emperorliu/djw | /app/helpers/application_helper.rb | UTF-8 | 1,076 | 2.90625 | 3 | [] | no_license | module ApplicationHelper
def minutes(time)
Time.at(time).strftime("%M:%S")
end
def percent(decimal)
(decimal*100).round
end
def mode(num)
if num == 1
"B"
else
"A"
end
end
def year(date)
date.first(4)
end
def harmonic_mixing(key)
if key.include? 'B'
ca... | true |
14297a2bbf028e8747f53e724572f13bde3e178c | Ruby | postazure/Ruby-Practice | /Second Run/CH8_FTT-1_sort.rb | UTF-8 | 948 | 3.984375 | 4 | [] | no_license | #Sort Words
def getWords
word = 'new words'
words_to_sort = []
while (!word.empty?)
print "Enter Word >>"
word = gets.chomp.capitalize
puts
words_to_sort.push word
end
return words_to_sort
end
def sort_array(sortMe)
ordered_array = []
while !sortMe.empty?
if ordered_array.empty?
... | true |
91ff0d364be6e6d7ea15dd338207beb350ed07fc | Ruby | jpfuentes2/elo | /lib/elo/player.rb | UTF-8 | 3,101 | 3.09375 | 3 | [
"MIT"
] | permissive | module Elo
# A player. You need at least two play a Game.
class Player
include Helper
# The rating you provided, or the default rating from configuration
def rating
@rating ||= Elo.config.default_rating
end
# The number of games played is needed for calculating the K-factor.
def game... | true |
3bb230db086ab83a30ff09a9be922c900a312c91 | Ruby | Joe-noh/railstutorial | /app/models/star.rb | UTF-8 | 527 | 2.53125 | 3 | [] | no_license | class Star < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
validates :date, presence: true
validates :status, presence: true, inclusion: {in: %i[candidate accepted declined]}
def status
read_attribute(:status).to_s.to_sym
end
def candidate?; status == :candidate end
def acce... | true |
a7824c9040795afb219f17c517618660aa40c10f | Ruby | MurasakiArtemis/compiladores-practica1 | /automaton.rb | UTF-8 | 3,632 | 3.171875 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'node'
require_relative 'transition'
require_relative 'state'
# Class for handling the automaton, each one may have a different specification
class Automaton
attr_accessor :states, :symbols, :initials, :finals, :transitions, :errors
attr_accessor :open, :result, :nod... | true |
6722a9b19e78d5b5c4a39e550dd6870885f687f6 | Ruby | dalexj/mastermind | /message_printer.rb | UTF-8 | 2,588 | 3.1875 | 3 | [] | no_license | require_relative "color"
class MessagePrinter
attr_reader :stream
def initialize(stdout)
@stream = stdout
end
def give_space
stream.puts "\n\n\n\n".colorize(31)
end
def welcome
stream.puts "Welcome to MASTERMIND, SUCKER".colorize(Color::BLUE_BACKGROUND)
end
def initial_request
strea... | true |
303c77eac58dd9fc65cbfdb946602a6bc9c5cfc5 | Ruby | jonesga1/adventCalender2016 | /day6part2.rb | UTF-8 | 779 | 3.328125 | 3 | [] | no_license | file = File.new("day6text.txt", "r")
lineValues = []
col1 = []
col2 = []
col3 = []
col4 = []
col5 = []
col6 = []
col7 = []
col8 = []
while line = file.gets do
line.length.times do |n|
lineValues.push(line[n])
end
col1.push(lineValues[0])
col2.push(lineValues[1])
col3.push(lineValues[2])
col4.push(lineValues[3])... | true |
e83805f9cf85ce4ce32a1d5abdbfd8ba358e74f7 | Ruby | mantrala/benzboy | /test/car/car_test.rb | UTF-8 | 661 | 2.53125 | 3 | [
"MIT"
] | permissive | require './test/test_helper'
class BenzCarTest < Minitest::Test
def test_exists
assert Benzboy::Car
end
def test_it_gives_a_single_car
VCR.use_cassette('one_car') do
car = Benzboy::Car.find(68)
assert_equal Benzboy::Car, car.class
# Check that the fields are accessible by our model
... | true |
fe0c900cbf9b3b468fc70131418b5c46163da2de | Ruby | kotsolesya/TestTask | /task2.rb | UTF-8 | 127 | 3.46875 | 3 | [] | no_license | class Task2
ARR = [1,4,5,7,8,10,20]
def search(x)
ARR.bsearch_index{ |i| i >= x}
end
end
print Task2.new.search(7) | true |
e45af1a85da8239904273e7e13cb79a9b0bcc251 | Ruby | AustinJuliusKim/AustinK_WDI | /06_week/week_6_ruby_coding_challenges/array_to_hash.rb | UTF-8 | 413 | 4.5 | 4 | [] | no_license | # # Array to Hash
# --
# Create a method to_h that accepts a nested array, and converts it to a hash of key-value pairs.
# ```
# animals = [["cat", "dog"], ["duck", "cow"]]
# to_h(animals)
# #=> {"cat" => "dog", "duck" => "cow"}
# ```
# def to_h(input)
# *input
# end
animals = [["cat", "dog"], ["duck", "cow"... | true |
0946fcc76167fd80c28effa5825a7450dee0755d | Ruby | TechSoftCompute/gkrtalpha | /app/models/product.rb | UTF-8 | 985 | 2.59375 | 3 | [] | no_license | class Product < ActiveRecord::Base
attr_accessible :name, :price,:image ,:remote_image_url,:creator_id,:description,:category_id
mount_uploader :image,ImageUploader
belongs_to :creator,:class_name=>"User"
belongs_to :category
has_many :comments
validates :price, :numericality => {:message=>"Please Enter Nu... | true |
467a3bd3be5ced94a476b3122eabd32582cd099c | Ruby | Daniel57910/chitter-challenge | /dm-chitter/spec/units/login_spec.rb | UTF-8 | 517 | 2.5625 | 3 | [] | no_license | require 'Chitter'
describe "Login" do
subject(:login) {Login.new("tester123", "123abcdef")}
it "takes in the username and the password as credentials" do
expect(login.username).to eq "tester123"
expect(login.password).to eq "123abcdef"
end
describe "#correct_credentials?" do
it "raises an error ... | true |
4a0985a41660c1a52dea303c7515c0b2dee4942b | Ruby | runongirlrunon/hackerrank-30-days-of-code | /day-05.rb | UTF-8 | 119 | 3.046875 | 3 | [
"MIT"
] | permissive | #!/bin/ruby
n = gets.strip.to_i
(1..10).each do |multiplier|
puts "#{n} x #{multiplier} = #{n * multiplier}"
end
| true |
162a4721c1dce8763c2cc605135ee66930324c0d | Ruby | sup-heliotrope/turnsole | /lib/turnsole/fiberback.rb | UTF-8 | 1,091 | 2.921875 | 3 | [] | no_license | ### a Fiber backport for Ruby 1.8.
###
### an alternative is to use Threads a la https://gist.github.com/4631,
### but i like version better.
begin
require 'fiber'
rescue LoadError
class Fiber
def initialize
args, ex, @enter = callcc { |c| [nil, nil, c] }
unless @enter
begin
*v =... | true |
3fe7a8022625acaf9cd0d4baff25f600f07372ac | Ruby | jmsevold/chris_pine_exercises | /precourse-pine/9.5_exercises.rb | UTF-8 | 452 | 4.25 | 4 | [] | no_license | # # Improved ask method. That ask method I showed you was OK,
# but I bet you could do better. Try to clean it up by removing
# the answer variable. You’ll have to use return to exit from the loop.
def ask(question)
puts question
reply = gets.chomp.downcase
while true
if reply == 'yes'
return true
els... | true |
09b3ed0e67547f8c1d086d5132c014c69895e646 | Ruby | DouglasAllen/code-Programming_Ruby_3rd_ed | /Part_IV--Ruby_Library_Reference/ch27_Built-in_Classes_and_Modules/Alphabetical_Listing/Exception/StandardError/IndexError/IndexError/IndexError.rb | UTF-8 | 265 | 2.75 | 3 | [] | no_license | IndexError.public_methods(false).sort.each do |method|
puts method
end
puts
IndexError.public_instance_methods(false).sort.each do |method|
puts method
end
puts
IndexError.constants.sort.each do |constant|
puts constant
end
puts
puts IndexError.superclass | true |
cddbeaf28b0a2d21bdc21944b123b2d82bc2e8c1 | Ruby | jm/primadoro | /lib/primadoro.rb | UTF-8 | 2,758 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Primadoro
class <<self
def run
# TODO: Make each of these configurable
@views = [
Views::Tunes.new,
Views::Growl.new,
Views::Sound.new
]
@actions = {:break_time => 5, :pomodoro => 25}
while(true)
# TODO: Add action hooks later
... | true |
a39f8d314ace1d11173544e6803f77522e3b4572 | Ruby | Animog504/reverse-each-word-houston-web-071618 | /reverse_each_word.rb | UTF-8 | 379 | 3.640625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(string)
newString = ""
arrayString = string.split(" ")
arrayString.collect do |words|
words.reverse!
if words.include?("!") || words.include?("?") || words.include?(".")
newString += "#{words}"
else
newString += "#{words} "
end
end
return newStri... | true |
7958ceaef7e89c1f0fa23efb7ac727858de576a7 | Ruby | patmaddox/method_matching | /spec/pattern_match_spec.rb | UTF-8 | 1,816 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require File.dirname(__FILE__) + '/spec_helper'
describe "pattern_match" do
def o(&block)
Class.new(&block).new
end
def not_pattern_match
raise_error(/No pattern matching/)
end
it "should call the method when pattern is matched" do
o { pattern_match(:foo, Integer) { :integer } }.
foo(123)... | true |
073a112cbaedb354d1bf3e62cf64ff926cc73d10 | Ruby | tanaken0515/atcoder | /virtual-contests/pepabo/001/D.rb | UTF-8 | 425 | 3.453125 | 3 | [] | no_license | gets
sticks = gets.chomp.split(" ").map!(&:to_i).sort!.reverse!
h = Hash.new(0)
first = nil
second = nil
sticks.each do |length|
h[length] += 1
if h[length] == 2 and first.nil?
first = length.to_i
elsif h[length] == 2 and second.nil?
second = length.to_i
end
if h[length] == 4 and second.nil?
se... | true |
920c32f85fcbde70878f2a5d77ae8eb0d9386853 | Ruby | Scra3/job | /backend/spec/payment_action_spec.rb | UTF-8 | 3,371 | 2.84375 | 3 | [] | no_license | require 'driver'
require 'rental'
require 'car'
require 'payment_action'
require 'date'
RSpec.describe PaymentAction do
let(:three_days_period) {Date.today..Date.today + 2}
let(:driver) {Driver.new(three_days_period, 20)}
let(:car) {Car.new(1, 10, 15)}
let(:rental) {Rental.new(1, car, driver)}
describe '#as... | true |
157ae63144acdbf2d3151f23a4ad1ce748266616 | Ruby | thanhn2001/forge | /lib/forge/builder.rb | UTF-8 | 4,358 | 2.59375 | 3 | [
"MIT"
] | permissive | module Forge
class Builder
def initialize(project)
@project = project
@config = project.config
@assets = project.assets
@task = project.task
end
# Runs all the methods necessary to build a completed project
#
# @return [void]
def build
clean_all
File... | true |
dbccf9864238b1c8c9ccc63830194741ee71655c | Ruby | quincogdell/classwork | /w03/d2/morning_excercises/product_main.rb | UTF-8 | 180 | 2.90625 | 3 | [] | no_license | require_relative 'product'
p1 = Product.new(10.82, "Mm, yummy")
p p1
p1.price = 9001.00
p p1
p1.description = "Mm, not so yummy"
p p1
p p1.price
p p1.description
p p1.to_hash
| true |
34caaea9926ae32ffcd85f753cbb03bf1eaff18b | Ruby | kclowes/crm-data-challenge | /lib/crm_reporter.rb | UTF-8 | 908 | 2.953125 | 3 | [] | no_license | class CrmReporter
attr_reader :data
def initialize(data)
@data = data
end
def first_names
data[:people].map do |person|
person[:first_name]
end
end
def employments
results = []
data[:people].each do |person|
if person[:employments] != []
person[:employments].each d... | true |
ae7fc3b34728b4064b60510d740728cb10dd3b5e | Ruby | jcrueter/day-3-ruby-loops | /exercise.rb | UTF-8 | 131 | 3 | 3 | [] | no_license | counter = 0
loop do
counter = counter + 1
if counter.odd?
next
end
puts counter
if counter == 10
break
end
end
| true |
839a3aba1252727afd3ec0cf2050f7dd65ec1fdc | Ruby | adamgonlag/trading_cards | /models/character.rb | UTF-8 | 970 | 3 | 3 | [] | no_license | def all_characters()
run_sql("SELECT * FROM characters;").to_a
end
def get_characters(query)
query = "%#{query}%"
params = [query]
sql_query = "SELECT * FROM characters WHERE name ILIKE $1;"
run_sql(sql_query, params).to_a
end
def character_by_name(name)
params = [name]
sql_query = "SELE... | true |
74ef0f677a9449d75ff77289498b0f37fc7dc0e6 | Ruby | buren/site_health | /lib/site_health/timer.rb | UTF-8 | 788 | 2.59375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'time'
module SiteHealth
class Timer
attr_reader :started_at, :finished_at
def self.start
new.tap(&:start)
end
def self.measure(&block)
new.tap { |timer| timer.measure(&block) }
end
def measure
start
yield
finish
se... | true |
d65b07fd95e877b328cf616673c8410b682b6ee7 | Ruby | johnantoni/ruby.json | /solutions/Eric Mahurin/json_parser_bench.rb | UTF-8 | 2,067 | 3.171875 | 3 | [] | no_license | require 'benchmark'
class RandomJSON
def initialize(value=0)
@number = -1
@string = -1
@boolean = -1
@constant = -1
@value = value-1
end
def number
case (@number=(@number+1)%3)
when 0 : 0
when 1 : 1234
when 2 : 3.75e+1
end
end
def str... | true |
0d86af059ba4c76635f72527331069fecff2dc08 | Ruby | Cireou/programming-univbasics-nds-nested-arrays-iteration-lab-part-1-yale-web-yss-052520 | /lib/iteration_with_loops.rb | UTF-8 | 294 | 3.5625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def find_even_values(src)
# Given an Array of Arrays of Integers ( [ [10, 11], [99, 50, 3, 4], [23, 41] ] ):
#
# Output all even values in each nested array
row = 0
for r in 0...src.length do
for c in 0...src[r].length do
puts src[r][c] if src[r][c].even?
end
end
end
| true |
c2d7f504e849b2a43acdf0b2cf811b12d3803888 | Ruby | neginsky58/customer-portal | /app/models/circuit_traffic.rb | UTF-8 | 1,882 | 2.609375 | 3 | [] | no_license |
class CircuitTraffic < ActiveRecord::Base
self.table_name = 'circuit_traffic'
belongs_to :circuit
def h_time_tag
if time_tag =~ /^MO.*/ then
year, month = time_tag.scan(/^MO(\d+)\.(\d+)/).flatten
return "#{year}/#{month}"
end
end
def total
total_in + ... | true |
a403952b97f5cfa19e8e20af0759ec62f939713b | Ruby | jcasts/ua_tokenizer | /test/test_ua_tokenizer.rb | UTF-8 | 22,253 | 2.796875 | 3 | [
"MIT"
] | permissive | require "test/unit"
require "ua_tokenizer"
class TestUaTokenizer < Test::Unit::TestCase
def test_tokenize_4part_upper
tokens = UATokenizer.tokenize("SAMSUNG-GT-S5620-ORANGE")
expected = ["samsung", "gt", "s5620", "orange"]
assert_equal expected, tokens
end
def test_tokenize_3part_camel
tokens =... | true |
1a25846550389a1dee53fbe3e38d7e91da8ea400 | Ruby | chn-challenger/project_maths | /models/evaluate.rb | UTF-8 | 911 | 3.25 | 3 | [] | no_license | module Evaluate
# def evaluate(starting_value,steps)
# result = starting_value
# steps.each do |step|
# result = _evaluate_one_step(result,step)
# end
# return result
# end
def evaluate(steps)
result = steps.first.val
for i in 1..steps.length - 1
result = _evaluate_one_step(r... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.