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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b99d7bc3608b451871ecd747c13fca6ca95a995a | Ruby | jchu4483/ruby-music-library-cli-v-000 | /lib/musiclibrarycontroller.rb | UTF-8 | 2,047 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class MusicLibraryController
def initialize(path = './db/mp3s')
MusicImporter.new(path).import
end
def call
help
loop do
puts "Please enter a command:"
input = gets.chomp
case input
when "help"
help
when "list songs"
list_songs
when "list artists"
... | true |
a321b8a704c85ab885223a87113fea41c59c539b | Ruby | edgar/RRDSimple | /lib/rrdsimple.rb | UTF-8 | 2,053 | 2.640625 | 3 | [] | no_license | require 'rubygems'
gem 'redis', '>= 2.0.3'
require 'redis'
class RRDSimple
VERSION = "0.0.1"
def initialize(opts)
@buckets = opts[:buckets]
@step = opts[:step]
@debug = opts[:debug] || false
@db = opts[:db] || Redis.new
end
def current_epoch
Time.now.utc.to_i / @step
end
def current_... | true |
dd071d1d02312d3b9ac1b0a5eb750dbd5fee370d | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/src/1542.rb | UTF-8 | 187 | 3.03125 | 3 | [] | no_license | def compute(first, second)
arr1 = first.chars
arr2 = second.chars
length = 0
arr1.size.times do |i|
length += 1 unless arr1[i] == arr2[i]
end
length
end | true |
83d03b9cb1fdd06f79143a4add44df5c51a5b6cd | Ruby | DDarrow123/crud-with-validations-lab-nyc-web-091718 | /app/models/song.rb | UTF-8 | 841 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Song < ActiveRecord::Base
validates :title, presence: true
validates :title, uniqueness: {
scope: %i[release_year artist_name],
message: 'Artist cannot release the same song more than once in a year'
}
validates :artist_name, presence: true
validates :released, inclusion: { in: [true, false] }
... | true |
d58ad01f0b95b988734969ed2ffb8af9c4bec7e8 | Ruby | sogapalag/contest | /aizu/acpc2017day1/a.rb | UTF-8 | 73 | 2.9375 | 3 | [] | no_license | n=gets.to_i
s=gets.chomp
if k=s.index('xx')
puts k+1
else
puts n
end
| true |
e2957c4449b6edf4e534242f73e178e6fa7e2c76 | Ruby | danielng09/App-Academy | /w2d2 Chess/chess/lib/stepping_piece.rb | UTF-8 | 1,290 | 3.6875 | 4 | [] | no_license | require_relative "piece.rb"
class SteppingPiece < Piece
#deleted delta attribute
def initialize(color, pos, moved, board, type)
super(color, pos, moved, board)
@type = type
end
def display
case @type
when :knight
case @color
when :black
print "\u265E"
when :white
... | true |
78fb6588e8f3ece8f0872423e038474128c91fcc | Ruby | Jenna424/rails-github-api-v-000 | /app/controllers/repositories_controller.rb | UTF-8 | 2,969 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class RepositoriesController < ApplicationController
def index
response = Faraday.get("https://api.github.com/user") do |request|
request.headers['Authorization'] = "token #{session[:token]}"
request.headers['Accept'] = 'application/json' # tells GitHub's server that we'll accept JSON as a response
... | true |
13c20ac06e543f611b02723d4fcbff933d4a4670 | Ruby | foreverLoveWisdom/Ruby-Lab | /closures/ampersand_to_proc.rb | UTF-8 | 342 | 3.671875 | 4 | [] | no_license | [1, 2, 3].inject(0) { |result, element| result + element }
class Symbol
def to_proc
lambda do |x, args|
# puts "current object is: #{x}"
# puts "current argument is: #{args}"
# puts "the method is: #{self}"
x.send(self, *args)
end
end
end
puts([1, 2, 10, 20].inject(&:+))
puts(1.+(2)... | true |
e50bb16b217c26aa0e676ec6096a7cd53dd34411 | Ruby | guynicolas/blackjack | /blackjack_solution.rb | UTF-8 | 2,737 | 4.28125 | 4 | [] | no_license | # Interactive procedural blackjack game
# Calculating total
def calculate_total(cards)
# [['S', '6'], ['C', '8'], ...]
value_array = cards.map{ |e| e[1] }
total = 0
value_array.each do |card_value|
if card_value == "A" # Aces
total += 11
elsif card_value.to_i == 0 # Q, J, and K
... | true |
21103bbcf4b23876ee0d9e7a2751566a02799c1c | Ruby | usman-tahir/rubyeuler | /neweuler26.rb | UTF-8 | 731 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env ruby
# https://projecteuler.net/problem=26
require 'prime'
def phi(n)
t = []
n.prime_division.each { |e| t << (e[0] - 1); t << (e[0] ** (e[1] - 1)) }
t.inject(:*)
end
non_reptends = (1..1000).to_a - [7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167,
179, 181, 193, 223, 229, 233, 257,... | true |
143045bbc41be572b22fc008ee4e75b901f0c2a5 | Ruby | lsewilson/learn_to_program | /ch11-reading-and-writing/build_a_better_playlist.rb | UTF-8 | 511 | 2.828125 | 3 | [] | no_license | def music_shuffle filenames
num_of_shuffles = 0
n = filenames.length
shuffled = []
while num_of_shuffles <= 10
until n == 0
shuffled.push(filenames.delete_at(rand(n)))
n -= 1
end
num_of_shuffles += 1
end
shuffled
end
songlist = Dir['/Users/laurawilson/Music/**/*.{mp3,MP3,m4a,M4A,wma... | true |
12e24b740fc833e7a0eaebb892adc28b80a8d5ec | Ruby | Tenzinwangchuk95/poke_move_finder | /lib/poke_stats/moves.rb | UTF-8 | 892 | 3.375 | 3 | [
"MIT"
] | permissive | class PokeStats::Moves
def pokemon_movelist
puts "Enter the PokeDex number of the Pokemon you would like to know what moves it is able to learn"
puts "Enter 'exit' to exit"
PokeStats::API.new.pokemon_info
end
def number_input
number = gets.strip
if number =... | true |
7ca7843c15ef68e3fb2ce84ed6865751e3d56717 | Ruby | MahmudH/ruby-kickstart | /session2/3-challenge/8_array.rb | UTF-8 | 719 | 4.25 | 4 | [
"MIT"
] | permissive | # Given an array of elements, return true if any element shows up three times in a row
#
# Examples:
# got_three? [1, 2, 2, 2, 3] # => true
# got_three? ['a', 'a', 'b'] # => false
# got_three? ['a', 'a', 'a'] # => true
# got_three? [1, 2, 1, 1] # => false
def got_three? arr
i = 0
output = false
while i < arr... | true |
7f1c6baa0a6cbcf729d29666e94b391c421ce3c9 | Ruby | franktisellano/titlecase_checker | /title_case.rb | UTF-8 | 2,809 | 3.71875 | 4 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'formatador'
def url_array_from_file(f)
if File::exists?(f) && !File.zero?(f)
file = File.open(f, 'r')
data = file.read
file.close
return data.split("\n")
else
Formatador.display_line("[red]File does not exist or is empty.")
return false
en... | true |
7b46e43f7beab870b62e59b1c41ff1c09d60f76b | Ruby | plai217/project-euler-10001st-prime-e-000 | /lib/10001st_prime.rb | UTF-8 | 343 | 3.484375 | 3 | [] | no_license | # Implement your procedural solution here!
def prime_number_for(num)
nthprime = 0
counter = 2
until nthprime == num
if prime(counter)
nthprime += 1
end
counter +=1
end
counter - 1
end
def prime(num)
Math.sqrt(num).to_i.downto(2) do |x|
if num % (x) == 0
return false
end
... | true |
7922022e17815a527cf461dd9c6a621fc0d2b688 | Ruby | danilogcastro/teaching | /batch-760/regex/reboot/instacart/instacart.rb | UTF-8 | 1,537 | 3.78125 | 4 | [] | no_license | # DISPLAY WELCOME MESSAGE
puts "--------------------"
puts "Welcome to Instacart"
puts "--------------------"
# CREATE A HASH FOR THE STORE
STORE = {
kiwi: { price: 1.25, stock: 5 },
banana: { price: 0.5, stock: 3 },
mango: { price: 4, stock: 6 },
asparagus: { price: 9, stock: 2 }
}
# DISPLAY THE STORE TO THE U... | true |
3d00148b19667cfb01367eed40f318953c5521a5 | Ruby | andrewmpierce/MusicCollection | /music_collection.rb | UTF-8 | 1,385 | 3.71875 | 4 | [] | no_license | require './album'
class MusicCollection
attr_reader :collection
def initialize(collection = {})
@collection = collection
end
def add(title, artist)
album = Album.new(title, artist)
if @collection[title]
puts 'That title is already in your collection!'
else
@collection[title] = alb... | true |
7dce29a581fcad7f370e6162efbc61f1a7b851db | Ruby | deepak-webonise/Ruby | /shop_inventory/version2/modules/file_operations.rb | UTF-8 | 1,937 | 3.078125 | 3 | [] | no_license | # /usr/bin/ruby -w
# Fileoperations Module
module FileOperations
FILE_PATH = './database/'
def self.read_mode(file_name)
begin
File.open(FILE_PATH + file_name, 'r').readlines
rescue Exception => e
puts 'Error in reading file'
end
end
def self.write_mode(file_name)
File.open(FILE_PATH... | true |
7044d2aa32b372f422225291b54a88216f042dc2 | Ruby | davepodgorski/Ruby_Text_Adventure | /exercise2.rb | UTF-8 | 184 | 3.265625 | 3 | [] | no_license | puts 55 * 0.15
puts "apples" + 77.to_s
puts "The universe is #{45628 * 7839} years old."
#True!
puts (10 < 20 && 30 < 20) || !(10 == 11)
#https://www.youtube.com/watch?v=bnKaOo67mLQ
| true |
dd387e553d3b436e611f6d4f360b3aec6e135025 | Ruby | amaranth0203/Sources | /ruby/html.rb | UTF-8 | 527 | 2.6875 | 3 | [] | no_license | class Html
DEFAULT_BROWSER = 'firefox'
def run file , args
if args.empty ?
`#{DEFAULT_BROWSER} #{file}`
else
despatch_on_parameters file , args
end
end
def dispatch_on_parameters file , args
cmd = args.shift
send "do_#{cmd... | true |
87ba5d111bc991e5a4ea845b81aad6f04727966c | Ruby | codeforkansascity/Neighborhood-Dashboard | /lib/entities/multi_dataset_geo_json.rb | UTF-8 | 853 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'json'
module Entities
class MultiDatasetGeoJson < GeoJson
extend Utilities::AttributesList
include Utilities::AttributesListInstance
attr_accessor :datasets
def initialize(args = {})
super(args)
@datasets = []
end
def add_dataset(dataset)
@datasets.push(dataset)
... | true |
d27332515cbed522e99e0f4d6f91e8b029294709 | Ruby | garfiny/kinetic_stream | /lib/kinetic_stream/record_processor.rb | UTF-8 | 2,052 | 2.546875 | 3 | [
"MIT"
] | permissive | module KineticStream
# TODO failover, recovery, and load balancing functionality
class RecordProcessor
RUNNING = 'running'
CLOSED = 'closed'
READY = 'ready'
ABORT = 'abort_on_error'
attr_reader :status
def initialize(stream, shard, client)
@client = client
@stream = stre... | true |
f0e8ba7fe3c34e05bc4a3ba7c8c76ef305037629 | Ruby | yumojin/Example-Sketches | /samples/processing_app/basics/form/primitives.rb | UTF-8 | 637 | 3.09375 | 3 | [
"MIT"
] | permissive | # Primitives 3D.
#
# Placing mathematically 3D objects in synthetic space.
# The lights() method reveals their imagined dimension.
# The box() and sphere() functions each have one parameter
# which is used to specify their size. These shapes are
# positioned using the translate() function.
def setup
size 64... | true |
a5167362e01cb5ee293faaae624f15f002906cee | Ruby | 2called-chaos/MCIR | /lib/mcir/core/helper.rb | UTF-8 | 6,216 | 2.8125 | 3 | [
"MIT"
] | permissive | # Encoding: utf-8
class Mcir::Core
# Contains helper methods.
module Helper
# Log each line of the given string seperately.
#
# @param [String] str String to log per line.
def eachlog str
str.split("\n").each{|s| log(s) }
end
# Shows a warning message and/or the help and/or abort the ... | true |
ff3c20a478e374feb1d5be1608c4f7a97ae238a0 | Ruby | ken1882/MLPRPG_VODL | /Old Data Scripts/254_MOG_Boss_HP_Meter.rb | UTF-8 | 32,061 | 2.671875 | 3 | [] | no_license | #==============================================================================
# +++ MOG - Boss HP Meter (V1.5) +++
#==============================================================================
# By Moghunter
# https://atelierrgss.wordpress.com/
#============================================================... | true |
ae5f9ef0cab2e644354cdcea234b9bbfd59e9075 | Ruby | btreim/ruby | /RSpec/lib/string_calculator.rb | UTF-8 | 183 | 3.40625 | 3 | [] | no_license | class StringCalculator
def self.add(input)
if input.empty?
0
else
numbers = input.split(",").map{|num| num.to_i}
numbers.inject { |mem, num| mem + num }
end
end
end | true |
5abf6a6f07152fbdf890f3d77407598a2bcddeb3 | Ruby | m3talsmith/expectations | /lib/expectations/mock_recorder.rb | UTF-8 | 518 | 2.515625 | 3 | [
"Ruby"
] | permissive | module Expectations::MockRecorder
def receive!(method)
method_stack << [:expects, [method]]
self
end
def method_stack
@method_stack ||= []
end
def method_missing(sym, *args)
super if method_stack.empty?
method_stack << [sym, args]
self
end
def subject!
method_stack.... | true |
89b071e9936f8005cf8d6e791938b98df87102c5 | Ruby | LuciferBlade/Ruby-assignments | /ruby uzduotis 2/3/tc_ruby_2_3_re.rb | UTF-8 | 1,011 | 2.90625 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'ruby_2_3_re'
require 'test/unit'
# Unit test class
class TestSolutionFinder < Test::Unit::TestCase
def test_intro_message
assert(true, SolutionFinder.new.intro_message)
end
def test_count_signs
assert_equal(0, SolutionFinder.new.count_signs)
end
def ... | true |
d7f86957b011061eeeb5a6f84d1754fc0e214829 | Ruby | carloscortegagna/sigeol | /test/unit/building_test.rb | UTF-8 | 1,644 | 2.859375 | 3 | [] | no_license | #QuiXoft - Progetto ”SIGEOL”
#NOME FILE: building_test.rb
#AUTORE: Grosselle Alessandro
require 'test_helper'
class BuildingTest < ActiveSupport::TestCase
def setup
@b=Building.new
end
#test13: un oggetto con attributi nulli, non deve essere valido. Se non è valido non viene salvato
# nel database
test"Il c... | true |
d8c1aa4672116365a17843f6befa39b4243f001b | Ruby | docodon/hplanner_bakend | /lib/helper_functions.rb | UTF-8 | 316 | 3.21875 | 3 | [] | no_license | module HelperFunctions
def HelperFunctions.binary_search ar,val
lo , hi = 0 , ar.size - 1
while 1
mid = (lo + hi)/2
(lo..hi).each do |i|
return i if ar[i]>=val
end if hi-lo<=3
if ar[mid] > val
hi = mid
elsif ar[mid] == val
return mid
else
lo = mid + 1
end
end
end
end | true |
c9c3f57a1ae8981a63464305cbe0202e863ad0d8 | Ruby | wkoszek/sivers | /db-api/core/test.rb | UTF-8 | 4,215 | 2.703125 | 3 | [
"BSD-2-Clause"
] | permissive | require '../test_tools.rb'
class CoreTest < Minitest::Test
include JDB
def setup
@raw = "<!-- This is a title -->\r\n<p>\r\n\tAnd this?\r\n\tThis is a translation.\r\n</p>"
@lines = ['This is a title', 'And this?', 'This is a translation.']
@fr = ['Ceci est un titre', 'Et ça?', 'Ceci est une phrase.']
super... | true |
8adc264bd7ad39d64d8a9cebf6a8515cfdce717a | Ruby | Jevaughnmckenzie/oo-student-scraper-v-000 | /lib/scraper.rb | UTF-8 | 1,613 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'open-uri'
require 'pry'
require_relative '../config'
class Scraper
def self.scrape_index_page(index_url)
html = open(index_url)
nested_html = Nokogiri::HTML(html)
student_cards = nested_html.css('.student-card')
# binding.pry
scraped_array = []
student_cards.each do |student_card|... | true |
d1e9c94b20a524a522ffd6f6ca18b4a8cf5c8ef1 | Ruby | upenn-libraries/subpop | /app/models/content_type.rb | UTF-8 | 228 | 2.609375 | 3 | [] | no_license | class ContentType < ActiveRecord::Base
validates :name, uniqueness: true
validates :name, presence: true
def <=> other
self.sort_name <=> other.sort_name
end
def sort_name
self.name.sub /^\W+/, ''
end
end
| true |
bbfb55b397b0224d7e13b57c0914c299fafed18e | Ruby | TeddyBradsher/ruby-oo-fundamentals-classes-and-instances-lab-nyc01-seng-ft-071320 | /lib/person.rb | UTF-8 | 174 | 2.8125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Person
attr_accessor :name
def initialize (name)
@name = name
end
end
adele_goldberg = Person.new("adele goldberg")
alan_kay = Person.new("alan kay") | true |
1cb49d00d055edda016ffff9b72427d2c6c007b9 | Ruby | Supernich/internship_nvo | /Rakefile | UTF-8 | 1,396 | 2.703125 | 3 | [] | no_license | task :create_directory, [:dir_name] => :check_directory do |task, args|
if @dir_exist
p 'Directory already exist'
return
end
create_directory(args[:dir_name])
end
task :check_directory, :directory do |task, args|
check_directory(args[:dir_name] || args[:directory])
end
def create_directory(dir_path)
... | true |
2cb7be7d1ff8c1c23907d6194f46b01ef9ca0115 | Ruby | apeiros/halsbe | /implementation/lib/minheap.rb | UTF-8 | 1,234 | 3.453125 | 3 | [] | no_license | class MinHeap
attr_reader :heap
def initialize(size)
@heap = [nil]
end
def pop
value = @heap.at(1)
index = 1
child_index = nil
child_index_a = 2
child_index_b = 3
child_a = @heap.at(child_index_a)
child_b = @heap.at(child_index_b)
while child_a or child_b
if ... | true |
daec801d8ae2c4b050f604d7f15a79baa7cf7237 | Ruby | omnitest/fog-samples | /compute_v2/detach_volume.rb | UTF-8 | 2,035 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env ruby
# This example demonstrates how to manage volumes on an existing server instance.
#
# Services used:
# - [Delete Volume Attachment](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Volume_Attachment.html)
require 'fog'
require File.expand_path('../../sample_helper', __FILE__)... | true |
e6f279215867e7ea66246c9b121b14a0d47a3ec1 | Ruby | kbrock/wsdl_dsl | /app/models/simple_type_def.rb | UTF-8 | 1,617 | 2.53125 | 3 | [] | no_license | ## currently used for simple types
class SimpleTypeDef < NamespacedNode
def self.all
if not defined? @@types
@@types=[]
#skipped 'byte' 'decimal' 'integer' 'long' 'short' 'unsignedByte' 'unsignedInt' 'unsignedShort'
['boolean', 'dateTime','date','double', 'float','int', 'string', 'time', 'd... | true |
97ed9ca4ba40af99ca13695b721491be55d668e9 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/strain/3505bcb6f3444df69b94fa02b64e5948.rb | UTF-8 | 174 | 2.84375 | 3 | [] | no_license | class Array
def keep
each_with_object([]) do |item, object|
object << item if yield(item)
end
end
def discard
keep {|item| !yield(item)}
end
end
| true |
90f182b1a329a30207103f2198d44b5cda3825ee | Ruby | tky3a/spec | /lib/calc.rb | UTF-8 | 87 | 2.890625 | 3 | [] | no_license | class Calc
def add(a, b)
# 5 # 仮実装
a + b #明らかな実装
end
end
| true |
eaf5df35f2dc097bd8e087414840cfe52b22c931 | Ruby | jof/tommy | /lib/tommy/libtftp.rb | UTF-8 | 20,932 | 2.6875 | 3 | [] | no_license | #!/usr/bin/env ruby
# library for TFTP functions
require 'socket'
require 'timeout'
require 'stringio'
include Socket::Constants
class TFTPOpCode
RRQ = 1
WRQ = 2
DATA = 3
ACK = 4
ERROR = 5
OACK = 6
end
class TFTPException < Exception
end
class TFTPImplementation
attr_accessor :socket, :timeout, :cl... | true |
d957a2ed5ab0374033af776eec50442c823e7252 | Ruby | RomAnoX/appfuel | /lib/appfuel/storage/repository/expr.rb | UTF-8 | 2,707 | 3.125 | 3 | [] | no_license | module Appfuel
module Repository
# Domain expressions are used mostly by the criteria to describe filter
# conditions. The class represents a basic expression like "id = 6", the
# problem with this expression is that "id" is relative to the domain
# represented by the criteria. In order to convert tha... | true |
c73be37015e18a2c288fa19cd9204d4a45d732ff | Ruby | thomasbeckett/sparta_stuff | /week-8/data_parsing/json/mockaroo/lib/mockaroo.rb | UTF-8 | 2,464 | 3.09375 | 3 | [] | no_license | require 'json'
class Mockaroo
attr_accessor :mockaroo
def initialize json_file
@mockaroo = JSON.parse(File.read(json_file))
end
def get_company
@mockaroo.each do |company|
unless company["Company"].is_a? String
return false
end
end
return true
end
def get_features c... | true |
e9ff0448e2c8bacfc8ead2aa904f796ca3c7ef3a | Ruby | kousuke1201abe/intern-line-bot | /app/models/messaging_api_client.rb | UTF-8 | 1,502 | 2.578125 | 3 | [] | no_license | class MessagingAPIClient < Line::Bot::Client
attr_reader :request
def initialize(request:, &block)
super(&block)
@request = request
end
def reply
build_reply_messages if signatured?
end
private
def signatured?
validate_signature(
request.body.read,
request.env['HTTP_X_LINE_... | true |
18a696387c55a2ee0fdc7228bc56f2b3b552dd8d | Ruby | bitcoinctf/download_tv | /test/downloader_test.rb | UTF-8 | 5,474 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require "test_helper"
describe DownloadTV::Downloader do
config_path = File.realdirpath("#{__dir__}/test_config")
before do
Dir.chdir(__dir__)
create_dummy_config(config_path) unless File.exist?(config_path)
end
after do
File.delete(config_path) if File.exist?(config_path)
end
describe "when creating th... | true |
c84e3527faa87ee7519cd575a0e7adc9c53b2055 | Ruby | cdunn2001/Yapura | /lib/yapura/data_type.rb | UTF-8 | 334 | 2.5625 | 3 | [
"MIT"
] | permissive | module Yapura
class DataType
attr_accessor :id, :name, :type, :options
def initialize(type)
self.type = type
end
def []=(id, called, options = {})
self.name = called
self.id = id
self.options = options
self
end
def [](id, called)
self[id, called] = {}
... | true |
d33ef0028a00a6d734ad59ee3f619838b391ab50 | Ruby | aconstandinou/ls-exercises | /101_109_small_problems/medium_1/1000_lights.rb | UTF-8 | 331 | 3.4375 | 3 | [] | no_license | hash = Hash.new
(1..1000).each_with_index { |k, idx| hash[k] = 1 }
counter = 2
loop do
break if counter == 1001
hash.each do |k, v|
if k % counter == 0
if v == 1
hash[k] = 0
else
hash[k] = 1
end
end
end
counter += 1
end
lights_on = hash.select { |k, v| v == 1 }
puts... | true |
b760db9e467a4fed27c5be0e4ec9b798ec0d1df6 | Ruby | derouett/Exo_Tang_Hugues | /exo_10.rb | UTF-8 | 120 | 2.875 | 3 | [] | no_license | puts "En quelle année es-tu née ? ?"
annee_de_naissance = gets.chomp.to_i
date = 2017
puts date - annee_de_naissance
| true |
9a1eab69385ff65460c178bb7be3f8deedf23f64 | Ruby | briankennedy1/mlb-event-api | /db/add_pitcher_homers.rb | UTF-8 | 914 | 2.609375 | 3 | [
"MIT"
] | permissive | PLAYERS.each do |player|
all_hits = Event.find_by_sql("SELECT events.* FROM events WHERE
events.pit_id = '#{player}' AND events.event_cd = '23' ")
all_hits.sort! { |x, y| [x.game_date, x.id] <=> [y.game_date, y.id] }
pbar = ProgressBar.create(
starting_at: 0,
total: all_hits.length,
format: "Curre... | true |
f3e825adcd0c95571d449437d1ef318d2b074158 | Ruby | prabhu-sunderaraman/Advent_Of_Code | /2017/Ruby/2017_day_1_part_2.rb | UTF-8 | 1,009 | 4.3125 | 4 | [] | no_license | #http://adventofcode.com/2017/day/1
# Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of e... | true |
67fd4f77131c63cd467f214bcb1e43582070abd3 | Ruby | r00takaspin/appbooster-timeserver | /src/date_calculator.rb | UTF-8 | 1,055 | 3.59375 | 4 | [] | no_license | require 'tzinfo'
#
# Formatted date output depending on city name
#
class DateCalculator
attr_reader :date
attr_reader :cities
attr_reader :city_times
#
# Useful structure for storing city name and time
#
class CityTime
attr_reader :name
attr_reader :time
def initialize(name, time)
@n... | true |
e24007ac67fe0705e93afbf63b93e55e78a3cda6 | Ruby | Cfowke81/Connect-4 | /lib/board.rb | UTF-8 | 1,680 | 3.625 | 4 | [] | no_license | require 'pry'
require 'colorize'
require_relative './player'
require_relative './piece'
require_relative './board_space'
class Board
attr_accessor :board
def initialize(num_columns, num_rows)
@board = []
num_columns.times do
column = []
num_rows.times do
column << BoardSpace.new
... | true |
d4c6f7b64e6319467ba0a473f3f1292ba60816eb | Ruby | nwtnni/game-of-life | /game.rb | UTF-8 | 355 | 2.9375 | 3 | [] | no_license | #!/usr/bin/ruby
require "./game_board"
require "./game_view"
unless ARGV.length == 3 then
puts "Usage: ruby game.rb <m> <n> <density>"
Kernel.exit(-1)
end
m, n, density = ARGV
m = m.to_i
n = n.to_i
density = density.to_i
game = GameBoard.new(m, n, density)
view = GameView.new(game)
view.draw
loop do
sle... | true |
8622aead8049425c0dc1d446b6d2230a8b2b1f1c | Ruby | ThiagoCasao/api_cep | /app/services/comunicacao_viacep.rb | UTF-8 | 526 | 2.5625 | 3 | [] | no_license | class ComunicacaoViacep
def buscar(cep)
url = "https://viacep.com.br/ws/#{cep}/json/"
retorno = JSON.parse(Net::HTTP.get(URI(url)))
if retorno["erro"]
{ erro: 'CEP não existe' }
else
endereco = GravacaoViacep.new(retorno).gravar
{ end: endereco, municipio: endereco.cidade }
end... | true |
fc3834bf1d5eccdf800cfce86f4d8d4c40986757 | Ruby | jameswilliamiii/world_cup_cli | /lib/world_cup_cli.rb | UTF-8 | 723 | 2.796875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require_relative '../config/environment.rb'
banner = "* World Cup CLI: Quickly check table standings and scores *"
opt_parser = OptionParser.new do |opt|
opt.banner = ("\n" + "*" * banner.length + "\n" + banner + "\n" + "*" * banner.length).colorize(:light_blue)
opt.separator "Commands".col... | true |
64372bad9b531f71dc321f5db37879e709f23006 | Ruby | charliecorrigan/homework | /bad_connection.rb | UTF-8 | 504 | 3.40625 | 3 | [] | no_license | ready_to_quit = false
bye = 0
puts "HELLO, THIS IS A GROCERY STORE!"
until ready_to_quit do
input = gets.chomp
if input.empty?
puts "HELLO?!"
elsif input == input.downcase
puts "I AM HAVING A HARD TIME HEARING YOU."
elsif input == "GOODBYE!" && bye == 0
bye +=1
puts "ANYTHING EL... | true |
bb83c7b4dab1d59bc8139c0e818e7305d8f6bd1d | Ruby | fjordllc/bootcamp | /app/models/link_checker/extractor.rb | UTF-8 | 711 | 2.59375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module LinkChecker
module Extractor
MARKDOWN_LINK_REGEXP = %r{\[(.*?)\]\((#{URI::DEFAULT_PARSER.make_regexp}|/.*?)\)}.freeze
module_function
def extract_links_from_multi(documents)
documents.flat_map { |document| extract_links_from_a(document) }
end
def extr... | true |
33c34d37dc01db1817e931c9561096873be704ef | Ruby | Gargantua88/char_gen | /lib/spell.rb | UTF-8 | 313 | 3.015625 | 3 | [] | no_license | class Spell
attr_reader :name, :casting_time, :components, :duration, :range, :level
def initialize(name, casting_time, components, duration, range, level)
@name = name
@casting_time = casting_time
@components = components
@duration = duration
@range = range
@level = level
end
end | true |
46452be561ede027acbd3f3f23727f4daf82c1f8 | Ruby | netzay/diy-json-serializer-lab-v-000 | /app/serializers/product_serializer.rb | UTF-8 | 428 | 2.609375 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class ProductSerializer
def self.serialize(product)
# open brace
s_prod = '{'
# product data
s_prod += '"id": ' + product.id.to_s + ', '
s_prod += '"name": "' + product.name + '", '
s_prod += '"price": ' + product.price.to_s + ', '
s_prod += '"inventory": ' + product.inventory.to_s + ', '
... | true |
b29acb27ae7f49d3d46ffad5936df6be21d5e198 | Ruby | ndlib/sipity | /app/repositories/sipity/commands/permission_commands.rb | UTF-8 | 1,967 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | require 'active_support/core_ext/array/wrap'
module Sipity
# :nodoc:
module Commands
# Commands related to the permission model
#
# TODO: Need to come up with a better way of handling this. Exposing
# module functions and instance methods is a bit insane. It works, but
# increases coupling. Pos... | true |
428b7ea00a610cf49fb865e27aad7d9f5f728412 | Ruby | matos89/ruby-music-library-cli-v-000 | /lib/music_importer.rb | UTF-8 | 460 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class MusicImporter
attr_accessor :path
def initialize(path)
@path = path
end
def files
files = Dir.glob(@path + "/" + "*.mp3")
files.collect {|file| file.gsub(@path + "/", "")}
end
# Why is this considered hardcoded? because i didn't use @path?
# files.collect {|file| file... | true |
745c8dacb361ebc51c529adf144013ee2339e704 | Ruby | GikuyuNderitu/dojo_ruby | /tdd_1/ruby_tdd/apple_tree/spec_appletree.rb | UTF-8 | 1,998 | 3.046875 | 3 | [] | no_license | require_relative "appletree"
RSpec.describe AppleTree do
before(:each) do
@a1 = AppleTree.new
end
it "has an age attribute with getter and setter methods" do
@a1.age = 1
expect(@a1.age).to eq(1)
end
it "has a height attribute with only a getter method. You should raise a NoMethodError if anyone tries to s... | true |
e8775155682a7dfcbefd1abb477970bd1eaa1f66 | Ruby | Mr-Bowtie/Intro_to_programming | /variables/name.rb | UTF-8 | 189 | 3.71875 | 4 | [] | no_license | puts "What's your first name?"
first_name = gets.chomp
puts "Last name?"
last_name = gets.chomp
puts "Well howdy, #{first_name} #{last_name}"
10.times do
puts first_name + last_name
end
| true |
d8debac6dfd7921ae8d42ffdd1f78296ea5b0c1b | Ruby | sg552/iteye_blog_fetcher | /fetcher.rb | UTF-8 | 1,576 | 2.640625 | 3 | [] | no_license | # -*- encoding : utf-8 -*-
require 'nokogiri'
require 'httparty'
class Fetcher
include HTTParty
BASE_URL = 'http://sg552.iteye.com'
MAX_PAGE = 1
headers 'User-Agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Referer' => BASE_URL,
'Host'... | true |
e70534437511eff2687e6801c7482de9879129b3 | Ruby | eduardodeoh/RubyLearning | /Week3/Exercises/progExercise7.rb | UTF-8 | 4,872 | 3.8125 | 4 | [] | no_license | #
#Exercise7. First of all, I'd like to thank Peter Cooper for allowing me to use this exercise.
#
#The application you're going to develop will be a text analyzer. You will be working on it this and next week. Your Ruby code will read in text supplied in a separate file, analyze it for various patterns and statistics,... | true |
1f9b078153a7efa0f7ee09b39857ad51f4724304 | Ruby | lyuehh/vimwiki | /ruby.md | UTF-8 | 1,458 | 2.734375 | 3 | [] | no_license | ## Ruby
### vim
`# vim: set ft=ruby:`
### rake参数
```ruby
task :test, :p1 do |t, args|
puts args[:p1]
end
rake test["test"] # -> "test"
```
更好的方式
`$ ver=20130101 rake test`
```ruby
ver = ENV['ver'] # -> '20130101'
```
### 更新vagrant 虚拟机中的vbox guest 版本
`gem install vagrant-vbguest`
### 多行注释
```ruby
=begin
def a... | true |
6e793d736bbb25ff4cd7d6bd0e86884c67280786 | Ruby | SaturdayAM/ruby-objects-has-many-lab-dc-web-031218 | /lib/author.rb | UTF-8 | 587 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
require_relative 'post.rb'
class Author
attr_accessor :name, :posts
#Class vars
@@post_count = 0
ALL_POSTS = []
def initialize(name = nil)
#instance vars
@name = name
@posts = []
end
#Add post object
def add_post(post_obj)
self.posts << post_obj
post_obj.author = self
post_obj
end... | true |
f2f1672c169ad3b6f1802db3714d765080f2883b | Ruby | mzulli/ruby-misc | /reverse_words_mod.rb | UTF-8 | 199 | 3.3125 | 3 | [] | no_license | def reverse_words_mod(str)
word_array = str.split
word_array = word_array.map do |word|
if word[0] != '@' || word[0] != '#'
word.reverse
end
end
str = word_array.join(' ')
return str
end | true |
a1587220ee7e9411287ec68e9687ad5dd82448ad | Ruby | JudeQuintana/service_monitor | /lib/service_monitor/service_control.rb | UTF-8 | 2,017 | 2.765625 | 3 | [
"MIT"
] | permissive | module ServiceMonitor
class ServiceControl
attr_accessor :service_name, :service_start, :service_stop, :service_status
STATUSES = [
OKAY = 'OK',
RUNNING = 'RUNNING',
STOPPED = 'STOPPED',
DEAD = 'DEAD',
FAILED = 'FAILED'
]
def self.build(config)
new(:service... | true |
c31bb5438cb3c0cd711173aef18ee15ddab77895 | Ruby | syagi/aoj | /alds1_6_C.rb | UTF-8 | 1,039 | 3.796875 | 4 | [] | no_license | class Card
attr_reader :suit, :number
def initialize(suit, number)
@suit = suit
@number = number.to_i
end
def <=(other)
@number <= other.number
end
def prints
print "#{suit} #{number}\n"
end
def <=>(other)
@number - other.number
end
end
def quick_sort(a,... | true |
fb480ef9963ee9b10f559d9e663cc59dfa71990e | Ruby | shyouhei/crypt_checkpass | /lib/crypt_checkpass/sha2.rb | UTF-8 | 4,875 | 2.59375 | 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) 2018 Urabe, Shyouhei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software an... | true |
05270e1411f1f1716b2b6110ed0efe2af11a2dd1 | Ruby | fabcipriano/hello-ruby-test | /utils/httptest.rb | UTF-8 | 1,646 | 2.828125 | 3 | [] | no_license | require 'rest_client'
require 'pp'
class MyTimer
def initialize()
@run = true
end
def repeat_every(interval)
#Ctrl-C
Signal.trap("INT") { stop() }
Signal.trap("TERM") { stop() }
while @run do
start_time = Time.now
yield
elapsed = Time.no... | true |
699d87a87f76e2c205e2e1ea67390868b6046804 | Ruby | wise-king-sullyman/chess | /lib/game.rb | UTF-8 | 3,408 | 3.4375 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'board'
require_relative 'player'
require_relative 'ai'
require_relative 'move_validation'
require_relative 'saving_and_loading'
require_relative 'check_detection'
# manage the game
class Game
include MoveValidation
include SavingAndLoading
include CheckDetection
... | true |
392200d9576dd4ba2b16637f172c032db48952df | Ruby | edisonesc/Learn_To_Code_With_Ruby | /The_First_And_Last_Method.rb | UTF-8 | 288 | 3.671875 | 4 | [] | no_license | arr = [1,2,3,4,5,6,7,8]
p arr.first(1) #First 3
p arr.last (1) #last 3
p arr.first
p arr.last
def custom_first(arr, num = 0)
p num != 0 ? arr[0, num] : arr[0]
end
def custom_last(arr, num = 0 )
p num != 0 ? arr[-num..-1] : arr[-1]
end
custom_first(arr, 3)
custom_last(arr, 4)
| true |
ee14d93ea855359409168ebc00c7473d502ed668 | Ruby | santiagoladavaz/katas-eis | /tenis/spec/marcador_spec.rb | UTF-8 | 3,324 | 2.890625 | 3 | [] | no_license | require 'rspec'
require_relative '../model/marcador'
require_relative '../model/jugador'
require_relative '../model/partido'
describe 'Marcador' do
describe 'initialize' do
it 'deberia comenzar con games 0-0' do
marcador = Marcador.new
marcador.games.count.should eq 0
end
it 'deberia comenzar con sets ... | true |
9c9639a27c1a1d61acd81a99cc9374c83a07c907 | Ruby | rossenhansen/Ruby | /079_CONDITIONAL_ASSIGNMENT_operator.rb | UTF-8 | 718 | 2.953125 | 3 | [] | no_license | <<<<<<< HEAD
# y = nil
# p y
# y ||= 5 #IfNill: Assign the value only if the value is nil
# p y
# y ||= 10 #Does not assign the value 10 to y
# p y
greeting = "Hello"
extraction = 10 #valid values (0,1,2,3,4)
letter = greeting[extraction] #gets letter at position extraction
letter ||="not found" #IfNill: display <<not ... | true |
f3032f61db7708df6f43bcbf45fd40c7490b952e | Ruby | slavakisel/coursera-ruby-starters | /data-structures/week2/build_heap.rb | UTF-8 | 581 | 3.703125 | 4 | [] | no_license | n = gets.to_i
data = gets.split(' ').map(&:to_i)
swaps = []
# The following naive implementation just sorts
# the given sequence using selection sort algorithm
# and saves the resulting sequence of swaps.
# This turns the given array into a heap,
# but in the worst case gives a quadratic number of swaps.
#
# TODO: rep... | true |
edefb0a07a6d92a289daef2d3c2d121a368f8245 | Ruby | rleer/diamondback-ruby | /tests/parser/large_examples/test_alias.rb | UTF-8 | 647 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | require 'test/unit'
class TestAlias < Test::Unit::TestCase
class Alias0
def foo; "foo" end
end
class Alias1<Alias0
alias bar foo
def foo; "foo+" + super end
end
class Alias2<Alias1
alias baz foo
undef foo
end
class Alias3<Alias2
def foo
defined? super
end
def bar
... | true |
b0f7cbf0a1146d5402d1e59338ba8325c01a09b4 | Ruby | aspiers/mutt.pub | /bin/create-gmail-month-filters | UTF-8 | 1,669 | 2.90625 | 3 | [] | no_license | #!/usr/bin/ruby
#
# Create gmail filters file for import into gmail web UI
# via gmail labs 'import/export filters' feature.
#
# Note that importing these filters and selecting the "Apply new
# filters to existing email" checkbox will cause *all* messages in an
# existing discussion thread to receive the new label, whi... | true |
834c78034ef4ca378412986389107f51f50ff905 | Ruby | uwgnol1612/Tic-Tac-Toe | /human_player.rb | UTF-8 | 293 | 3.8125 | 4 | [] | no_license |
class HumanPlayer
attr_reader :mark
def initialize(mark, board)
@mark = mark
@board = board
end
def display
@board.print
end
def get_move
puts 'Please give two numbers (0-2) seperated by a space, ex. 1 2'
move = gets.chomp.split(" ").map(&:to_i)
end
end | true |
9b44040f14ce71b114b00cef2341e1b31bd3ceb2 | Ruby | svenyurgensson/candy | /lib/candy/factory.rb | UTF-8 | 1,314 | 3.25 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'candy/qualified_const_get'
module Candy
# Utility methods that can generate new methods or classes for some of Candy's magic.
module Factory
# Creates a method with the same name as a provided class, in the same namespace as
# that class, which delegates to a given class method of that class. (W... | true |
bbf770a0cebad34039b7659c636880622c89e50f | Ruby | viktorrehnqvist/fifaappen | /app/models/achievements/big_wins_night_achievement.rb | UTF-8 | 744 | 2.671875 | 3 | [] | no_license | class BigWinsNightAchievement < Achievement
def self.check_conditions_for(player)
# Check if achievement is already awarded before doing possibly expensive
# operations to see if the achievement conditions are met.
@achievement = false
if player.big_score_by_night
player.award(self)
@achievement = true
... | true |
cd6268f2953c1b3f0a0539d04d79c13b0951dc48 | Ruby | MarielJHoepelman/square_array-v-000 | /square_array.rb | UTF-8 | 110 | 3.375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
squares = Array.new
array.each do |n|
squares.push(n**=2)
end
squares
end
| true |
2d3dfb73d8db50c959846b964b5a56aea739bb0a | Ruby | SahanaSanjeeva/TWB-Recorder | /web/lib/users.rb | UTF-8 | 292 | 2.53125 | 3 | [
"MIT"
] | permissive | class Users
attr_reader :path
def initialize path
@path = path
end
def map_uuids
Dir["#{path}/users/*/metadata.json"].inject([]) do |result, file|
file.gsub! %r{/metadata.json}, ''
uuid = File.basename file
result << yield(uuid)
end
end
end | true |
fc350ba37d53dccbd8cf3882b55e60914649cc2c | Ruby | nicoledow/programming-univbasics-4-square-array-online-web-prework | /lib/square_array.rb | UTF-8 | 224 | 3.734375 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def square_array(array)
counter = 0
array_of_squares = []
while counter < array.length
square_num = array[counter] * array[counter]
array_of_squares << square_num
counter += 1
end
array_of_squares
end | true |
0aea2655cb58a83805c95ee36feb50e7540476cb | Ruby | Tsutomu19/StudyingAlgorithms | /0512.rb | UTF-8 | 6,857 | 3.546875 | 4 | [] | no_license | # 23:30 堀越 優希
data = gets.split(" ").map(&:to_i)
student_count = data[0]
question_count = data[1]
student_data = (1..student_count).map{gets.chomp!.split(" ").map(&:to_i)}
@single_point = 100 / question_count
def calc(delay,collect)
score = collect * @single_point
if delay >= 1 && delay <= 9
score *= ... | true |
8c12a6bce43f81566a1ac4c1f3cf2bb4f93be75b | Ruby | wave2future/fingerpoken | /lib/fingerpoken/target.rb | UTF-8 | 2,048 | 2.96875 | 3 | [] | no_license | require "logger"
class FingerPoken::Target
def initialize(config)
@channel = config[:channel]
@logger = Logger.new(STDERR)
@logger.level = ($DEBUG ? Logger::DEBUG: Logger::WARN)
end
def register
if @registered
@logger.warn("Ignoring extra call to #{self.class.name}#register. Trace:\n#{call... | true |
793eda16e1414b516a63d81a2403b3228587c673 | Ruby | charleschu/tianya-topic-text | /tianya.rb | UTF-8 | 3,327 | 2.640625 | 3 | [] | no_license | #encoding: utf-8
require 'debugger'
require 'nokogiri'
require 'open-uri'
time_start = Time.now
#url = "http://bbs.tianya.cn/post-develop-1868959-1.shtml"
class Topic
attr_accessor :author_id, :text, :pages
# REPLY_REGEX = /^(\r\n\t\t\t\t\t\t\t\u3000\u3000)@(.+\s(\d+\u697C)?.+)/
# REPLY_REGEX = /^(\r\n\t\t\t\t\t... | true |
7ce937c26373b06a3ffe69a1e9b52020d25453c6 | Ruby | kswang2400/app-academy-kwang | /week-1-day-5/knight.rb | UTF-8 | 1,790 | 3.625 | 4 | [] | no_license |
require './00_tree_node.rb'
class KnightPathFinder
attr_accessor :visited_positions
attr_reader :start_position, :root
def initialize(start_position)
@start_position = start_position
@visited_positions = [start_position]
@root = build_move_tree
end
def self.valid_moves(pos)
possible_moves ... | true |
73b364252bf82a2a2832fcdc00b75ba0cddc96f1 | Ruby | chmodawk/Study_Ruby | /基本语法/异常处理.rb | UTF-8 | 1,278 | 3.640625 | 4 | [] | no_license | # 当错误触发时,会有两个变量被自动赋值:
# $! :最后一次发生的异常(对象)
# $@ :最后一次发生异常的位置信息
# 异常对象具有方法:
# class 异常种类
# message 异常信息
# backtrace 异常发生的位置信息($@与此等价)
# rescue 有对应的修饰符,如下:
# 如果出错,就赋值为后面的值
a = Integer("abc") rescue 0
# 可以将该错误赋值到变量里,使用如下方法
# rescue => ex (用于多个错误对象的分别捕获)
begin
rescue NoMethodError, NameError => e1
e1
... | true |
c08323b929bda6e0effbc544314820415580c38d | Ruby | EricPMulligan/best_quotes | /sqlite_test.rb | UTF-8 | 699 | 3.015625 | 3 | [] | no_license | require 'sqlite3'
require 'rulers/sqlite_model'
class MyTable < Rulers::Model::SQLite
def method_missing(name, *args, &block)
method = name.to_s
if self.class.schema.has_key?(method)
self.class.instance_eval do
define_method(method) { @hash[method] }
end
self.send(method)
end
... | true |
29d4cfb21b60edf4cfea981ef643954f885a3f44 | Ruby | skroutz/string_metric | /benchmarks/dictionary.rb | UTF-8 | 1,194 | 2.796875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'string_metric'
require 'benchmark'
require 'pp'
Benchmark.bmbm(7) do |x|
options = {}
max_distance = 2
dict = []
trie = StringMetric::Levenshtein::TrieNode.new
File.open('/usr/share/dict/words', 'r').each_line do |line|
word = line.chomp
trie.insert(word)
dict << word
end
randomWor... | true |
413978bacbd7dfcdeba76b4434f2b113378cb6c7 | Ruby | bangms92/whois-store | /app/models/domain.rb | UTF-8 | 383 | 2.5625 | 3 | [] | no_license | require 'whois'
class Domain < ApplicationRecord
validates_format_of :name, :with => /\A(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$\Z/
def populate
name = self.name
record... | true |
2e56fd7e85b45430ef51f14e541c39a8bce90385 | Ruby | Kirill-lesnikh/CucumberLearn | /features/pages/my_content.rb | UTF-8 | 1,681 | 2.609375 | 3 | [] | no_license | require_relative 'video_list_channels'
class MyContent < VideoListChannels
# Elements
def btn_edit_properties
browser.element(xpath:"//ul[contains(@class, 'allego-index-menu')]//span[contains(., 'Edit properties')]/..")
end
def btn_make_a_copy
browser.element(xpath:"//ul[contains(@class, 'allego-inde... | true |
e73ce26bffc31c075c1dcf8a1ce0d77cc698ce48 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/gigasecond/a0a5707ed02d4231a2569e2320b7d9c3.rb | UTF-8 | 248 | 3.265625 | 3 | [] | no_license | class Gigasecond
def initialize(date)
@date = date
end
def date
Time.at(anniversary_in_seconds).to_date
end
private
def anniversary_in_seconds
seconds + 1_000_000_000
end
def seconds
@date.to_time.to_i
end
end
| true |
fda872d9a37e3f9d6a155663a2413cae6397fdae | Ruby | emmiehayes/little-shop-redux | /spec/models/merchant_spec.rb | UTF-8 | 5,049 | 2.625 | 3 | [] | no_license | RSpec.describe Merchant do
describe "Validations" do
it "should have a name" do
merchant = Merchant.new(name: nil)
expect(merchant).to_not be_valid
end
end
describe "Instance Methods" do
it ".total_merchant_items" do
merchant_1 = Merchant.create(name: "Dogs4Life")
merchant_2 ... | true |
d9404c89961892bf422473ea087457e0fdee802c | Ruby | manavt/Bunny | /lib/import.rb | UTF-8 | 453 | 2.53125 | 3 | [] | no_license | class Import
def self.import_from_link
r = RestClient.get ("http://localhost:4000/products/download_in_json.json")
data = JSON.load(r.body)
data.each do | each_record |
each_record.delete_if {|key, _| key == "id"}
if p = Product.create!(each_record)
Rails.logger.info "Successfully sav... | true |
e7b10b5f3c6e02419f2ff0c9a0d18aac2f0496f5 | Ruby | HirokiTachiyama/jack-of-all-trades | /functions/todo.rb | UTF-8 | 835 | 3.078125 | 3 | [] | no_license | # coding: utf-8
=begin
***
*** File name: todo.rb
*** Create: 2016, 11/2(Wed) 00:54
*** Author: Hiroki Tachiyama
***
* DO NOT USE CYGWIN TERMINAL !! to operate mysql and ruby gem while development.
* -> To operate mysql, use MySQL Workbench or of MySQL's terminal.
* -> To operate ruby gem, use Ruby's terminal.... | true |
903e0efbe6f2ba8039a4c6e74627550d9bbd1d62 | Ruby | bstiber/launch_school_exercises | /small_problems_2nd_round/ruby_basics/loops2/4.rb | UTF-8 | 672 | 4.71875 | 5 | [] | no_license | # Get the Sum. The code below asks the user "What does 2 + 2 equal?" and uses #gets to retrieve
# the user's answer. Modify the code so "That's correct!" is printed and the loop stops when
# the user's answer equals 4. Print "Wrong answer. Try again!" if the user's answer doesn't
# equal 4.
# input
# - 'user answer', ... | true |
8b6a6bcc86ba489193ce2c70b418b9932e8ebb03 | Ruby | brundage/odifferous | /old_stuff/bin/processYtube.rb | UTF-8 | 841 | 2.78125 | 3 | [] | no_license | #!/usr/bin/ruby
require 'csv'
require 'pp'
require 'y_tube_fly'
if ARGV[0].nil?
p "Need ARGV[0]"
exit 2
else
infilename = ARGV[0]
end
today = Time.now.strftime("%Y-%m-%d")
outfilename = ARGV[1].nil? ? "#{File.basename(infilename)}-output-#{today}.csv" : ARGV[1]
infile = File.open( infilename, "rb" )
outfile ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.