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
b29106ab72aa2807550d0a8ebf93170a954b800c
Ruby
levthedev/intro_to_ruby
/oldboobina.rb
UTF-8
712
4
4
[]
no_license
# Write a Deaf Grandma program. # Whatever you say to grandma # (whatever you type in), # she should respond with HUH?! # SPEAK UP, SONNY!, unless you # shout it (type in all capitals). # If you shout, she can hear you # (or at least she thinks so) # and yells back, NO, NOT SINCE # 1938! # # "You can't stop talking to # grandma until you shout BYE. # She should say 'LEAVING SO SOON?' # When you say 'BYE' again, she says 'BYE LIL BOOBNOS' and the program exits ready_to_quit = false puts "HEY LITTLE BOOBNOS!" input = gets until ready_to_quit unless input == input.upcase puts "HUH?! SPEAK UP, BOOBOS" input = gets else puts "NO, NOT SINCE 1938" input = gets end end puts "LATER,BOOBAY!"
true
7c769851bd23e54f872459a10af062a85f408944
Ruby
vmetrix/vacuumetrix
/bin/NewrelicThresholds.rb
UTF-8
1,930
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby ### grab metrics from newrelic and put them into graphite ### David Lutz ### 2012-06-15 ### to use: apt-get install ruby ### apt-get install build-essential ### apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev ### gem install curl curb json xmlsimple --no-ri --no-rdoc # $:.unshift File.join(File.dirname(__FILE__), *%w[.. conf]) $:.unshift File.join(File.dirname(__FILE__), *%w[.. lib]) require 'config' require 'rubygems' if RUBY_VERSION < "1.9" require 'curb' require 'json' require 'xmlsimple' require 'Sendit' t=Time.now.utc $timenow=t.to_i def GetThresholdMetrics(application, appname) begin threshURL= "https://rpm.newrelic.com/accounts/"+$newrelicaccount+"/applications/"+application+"/threshold_values.xml" response = Curl::Easy.perform(threshURL) do |curl| curl.headers["x-api-key"] = $newrelicapikey end body=response.body_str data = XmlSimple.xml_in(body, { 'KeyAttr' => 'threshold_values' }) raise 'No data returned from New Relic API' if data['content'] === "\n" raise "Error returned from New Relic API: #{data['content']}" if data['content'] data['threshold_value'].each do |item| Sendit "newrelic." + appname.gsub( /[ \.]/, "_") + "." + item['name'].gsub(" ","_"), item['metric_value'], $timenow.to_s end rescue Exception => e puts "Error processing app \"#{application}\" \"#{appname}\": #{e}" end end ##get a list of applications for account X applicationsURL = "https://rpm.newrelic.com/accounts/"+$newrelicaccount+"/applications.xml" appsresponse = Curl::Easy.perform(applicationsURL) do |curl| curl.headers["x-api-key"] = $newrelicapikey end appsbody=appsresponse.body_str appdata = XmlSimple.xml_in(appsbody, { 'KeyAttr' => 'applications' }) ## big ole loop over the returned XML appdata['application'].each do |item| appname = item['name'][0].to_s application=item['id'].to_s.gsub!(/\D/,"").to_i.to_s GetThresholdMetrics application, appname end
true
8650f8ab1cfe75dbc8212f2cd7e58595c368bc03
Ruby
marcusfgardiner/student-directory
/source_code_reader.rb
UTF-8
345
4.0625
4
[]
no_license
#Quines i.e. printing a programs own source code! #Key is properly escaping characters to reprint code #The first line of code is very close to the second but with lots of escaping characters e.g. \n, and .inspect is used to escape the string itself. quine = "\nputs \"quine = \" + quine.inspect + quine" puts "quine = " + quine.inspect + quine
true
d043170712de9b2a2ac9f854e086adad9e0984db
Ruby
sbraford/pubrunner
/test/test_octopress_transformer.rb
UTF-8
1,432
2.609375
3
[ "MIT" ]
permissive
require 'test/unit' require 'pubrunner' class OctopressTransformerTest < Test::Unit::TestCase include Pubrunner def test_octopress_transform_and_save wellformatted_path = File.dirname(__FILE__) + '/fixtures/wellformatted.txt' p = Processor.new(wellformatted_path) b = p.process ot = Transformer::Octopress.new(b) target_dir = File.dirname(__FILE__) + '/fixtures/octopress' ot.transform_and_save(target_dir) octo_posts_path = File.join(target_dir, '*.html') Dir[octo_posts_path].entries.each do |f| if f.include?('chapter-title') chapt_one = IO.read(f) assert chapt_one.include?('<strong>Bold text</strong>') assert chapt_one.include?('<em>Italics text</em>') elsif f.include?('chapter-2') chapt_two = IO.read(f) assert chapt_two.include?('Day &amp; Night') assert chapt_two.include?('&lt;special&gt; characters') end end assert_equal 3, Dir[octo_posts_path].entries.size Utils.clean_folder(target_dir) end def test_octopressify_filename wellformatted_path = File.dirname(__FILE__) + '/fixtures/wellformatted.txt' p = Processor.new(wellformatted_path) b = p.process t = Time.now ot = Transformer::Octopress.new(b) fname = ot.octopressify_filename(b.chapters[0].title, t) date = t.strftime("%Y-%m-%d") assert_equal "#{date}-this-is-a-chapter-title.html", fname end end
true
0d2b5cc41358fdf7ee7d613dc0824355915eaa88
Ruby
arnelimperial/Ruby-codes
/fib.rb
UTF-8
477
3.84375
4
[ "Zlib" ]
permissive
#!/usr/bin/env ruby #Fibonacci function def fibonacci(int) if int == 1 return 1 end if int == 2 return 2 end # return return fibonacci(int - 1) + fibonacci(int -2) end #print w/o new line print "Montako kierrosta lasketaan?: " # convert to int w/out new line number = gets.chomp.to_i #for loop from 1 to the given num for i in 1..number do #display w/ new line ..puts puts "Seuraava Fibonaccin luku on #{fibonacci(i)}." end
true
7c2040e89d199a7bda88e87a1bdffdd1093a46fe
Ruby
niligulmohar/ruby_asound
/asound.rb
UTF-8
6,745
2.59375
3
[]
no_license
require 'forwardable' require '_asound' module Snd::Seq class << self def open Snd::Seq::SequencerClient.new end end class SequencerClient attr_reader :client_id def initialize @client_id = client_info.client end def create_simple_port(name, caps, type) port_info = PortInfo.new port_info.port = _create_simple_port(name, caps, type) Port.new(self, port_info) end def alloc_queue Queue.new(self, _alloc_queue) end def change_queue_tempo(q, tempo, ev = nil) _change_queue_tempo(q, tempo, ev) end def start_queue(q, ev = nil) _start_queue(q, ev) end def stop_queue(q, ev = nil) _stop_queue(q, ev) end def continue_queue(q, ev = nil) _continue_queue(q, ev) end def client_info client_info = ClientInfo.new get_client_info(client_info) return client_info end def each_port client_info = ClientInfo.new client_info.client = -1 while (0 == query_next_client(client_info)) next if client_info.client == @client_id port_info = PortInfo.new port_info.client = client_info.client port_info.port = -1 while (0 == query_next_port(port_info)) yield Port.new(self, port_info.clone) end end end def input_pending? event_input_pending(0) end end class Queue def initialize(seq, n) @seq = seq @n = n end def to_int() @n; end def ppq=(ppq) @seq.change_queue_ppq(@n, ppq) end def change_tempo(bpm, ev = nil) @seq.change_queue_tempo(@n, 60000000 / bpm, ev) end def tempo=(bpm) change_tempo(bpm) end def start(ev = nil) @seq.start_queue(@n, ev) end def stop(ev = nil) @seq.stop_queue(@n, ev) end def continue(ev = nil) @seq.continue_queue(@n, ev) end def tick_time @seq.queue_get_tick_time(@n) end end class Event alias_method :variable_data, :variable alias_method :to_port_subscribers!, :set_subs alias_method :direct!, :set_direct def self.def_type_checks(*name_syms) name_syms.each do |name_sym| name = name_sym.to_s class_eval("def #{name}?() type == Snd::Seq::EVENT_#{name.upcase} end") end end def_type_checks :sysex, :clock, :noteon, :noteoff, :keypress, :controller def_type_checks :pgmchange, :chanpress, :pitchbend def identity_request? sysex? and variable_data == "\xf0\x7e\x7f\x06\x01\xf7" end def identity_response? sysex? and variable_data =~ /^\xf0\x7e.\x06\x02.........\xf7$/ end def sysex_channel fail unless sysex? return variable_data[2] end def destination=(arg) set_dest(*arg) end def source_info port_info = PortInfo.new port_info.client = source[0] port_info.port = source[1] return port_info end def source_ids "[#{source[0]}:#{source[1]}]" end def channel _channel + 1 end def note_name n = note %w[C C# D D# E F F# G G# A A# B][n%12] + (n/12).floor.to_s end def channel_s "C:%02d" % channel end def to_s type = (if sysex? "System exclusive:#{variable_data.hexdump}" elsif noteon? "#{channel_s} Note #{note_name} " + (if velocity > 0 "on V:#{velocity}" else "off" end) elsif noteoff? "#{channel_s} Note #{note_name} off V:#{velocity}" elsif keypress? "#{channel_s} Key aftertouch" elsif controller? "#{channel_s} Continuous controller #{param}: #{value}" elsif pgmchange? "#{channel_s} Program change #{value}" elsif chanpress? "#{channel_s} Channel aftertouch: #{value}" elsif pitchbend? "#{channel_s} Pitch bend #{value}" else "Unknown" end) "%8d #{type}" % tick_time end end class PortInfo alias_method :capabilities, :capability alias_method :to_int, :port def clone copy = super copy.copy_from(self) return copy end def midi? type & PORT_TYPE_MIDI_GENERIC != 0 end def readable? capabilities & PORT_CAP_READ != 0 end def writable? capabilities & PORT_CAP_WRITE != 0 end def read_subscribable? capabilities & PORT_CAP_SUBS_READ != 0 end def write_subscribable? capabilities & PORT_CAP_SUBS_WRITE != 0 end end # A Port object is a PortInfo belonging to a certain # SequencerClient. Can output Events with itself as source. class Port attr_reader :seq, :port_info def initialize(seq, port_info) @seq = seq @port_info = port_info end def method_missing(sym, *args) @port_info.send(sym, *args) end def to_int @port_info.port end def connect_to(arg) if arg.kind_of?(PortInfo) @seq.connect_to(@port_info.port, arg.client, arg.port) elsif arg.kind_of?(Port) connect_to(arg.port_info) else @seq.connect_to(@port_info.port, *arg) end end def connect_from(arg) if arg.kind_of?(PortInfo) @seq.connect_from(@port_info.port, arg.client, arg.port) elsif arg.kind_of?(Port) connect_from(arg.port_info) else @seq.connect_from(@port_info.port, *arg) end end def event_output!(event_param = nil) event = event_param || Event.new yield event if block_given? event.source = port event.to_port_subscribers! @seq.event_output(event) @seq.drain_output end def ids "[#{@port_info.client}:#{@port_info.port}]" end end # A DestinationPort represents a port you want to send events to, # and contains a reference to the port you want to use as a source. class DestinationPort def initialize(port, source_port) @port = port @source_port = source_port end def method_missing(sym, *args) @port.send(sym, *args) end def event_output!(event_param = nil) event = event_param || Event.new yield event if block_given? event.destination = [@port.client, @port.port] event.source = @source_port.port @port.seq.event_output(event) @port.seq.drain_output end def ids "[#{@port.client}:#{@port.port}]" end end end
true
d38a98739ab48617e1eec2822b7becee752654c4
Ruby
alpaca-tc/ffaker
/lib/faker/utils/module_utils.rb
UTF-8
358
2.703125
3
[]
no_license
require 'ffaker/utils/array_utils' module Faker module ModuleUtils def fill_in_string(text, n = nil) return text if n.nil? max = n.is_a?(Range) ? n.to_a.shuffle.first : n until text.length == max return text[0...max] if text.length >= max text += text[0...max - text.length] end text end end end
true
25402e5cb85d3bd06a4abbf7a86b7b97a8a5ff0b
Ruby
dmaster18/learn-co-sandbox
/ruby_past_practice/self.rb
UTF-8
303
3.78125
4
[]
no_license
class Dog attr_accessor :name, :owner def initialize(name) @name = name end def call_on puts self end def get_adopted(owner_name) self.owner = owner_name end end fido = Dog.new("Fido") fido.owner = "Sophie" puts fido.owner fido.get_adopted("Anthony") puts fido.owner
true
94cd1aebba4efef6be9428172895301c54113d0a
Ruby
message-driver/message-driver
/spec/units/message_driver/middleware/middleware_stack_spec.rb
UTF-8
5,813
2.765625
3
[ "MIT" ]
permissive
require 'spec_helper' module MessageDriver module Middleware RSpec.describe MiddlewareStack do class Top < Base; end class Middle < Base; end class Bottom < Base; end let(:top) { Top.new(destination) } let(:middle) { Middle.new(destination) } let(:bottom) { Bottom.new(destination) } before do allow(Top).to receive(:new).with(destination).and_return(top) allow(Middle).to receive(:new).with(destination).and_return(middle) allow(Bottom).to receive(:new).with(destination).and_return(bottom) end def load_middleware_doubles subject.append Middle subject.prepend Bottom subject.append Top end let(:destination) { double(Destination) } subject(:middleware_stack) { described_class.new(destination) } it { is_expected.to be_an Enumerable } describe '#destination' do it { expect(subject.destination).to be destination } end describe '#middlewares' do it 'is initially empty' do expect(subject.middlewares).to be_an Array expect(subject.middlewares).to be_empty end it 'returns the list of middlewares' do load_middleware_doubles expect(subject.middlewares).to eq [bottom, middle, top] end it 'ensures the returned list of middlewares is frozen' do expect(subject.middlewares).to be_frozen end end shared_examples 'a middleware builder' do |op| it 'instantiates the middleware and passes the destination to it' do allow(Top).to receive(:new).and_call_original subject.public_send op, Top middleware = subject.middlewares.first expect(middleware).to be_an_instance_of Top expect(middleware.destination).to be destination end it 'returns the instantiated middleware' do expect(subject.public_send(op, Top)).to be top end context 'with a parameterizable middleware' do class Paramed < Base attr_reader :foo, :bar def initialize(destination, foo, bar) super(destination) @foo = foo @bar = bar end end it 'passes the extra values to the middleware initializer' do subject.public_send(op, Paramed, 27, 'a parameter value') middleware = subject.middlewares.first expect(middleware).to be_an_instance_of Paramed expect(middleware.foo).to eq(27) expect(middleware.bar).to eq('a parameter value') end end context 'with a hash of blocks' do let(:on_publish) { ->(b, h, p) { [b, h, p] } } let(:on_consume) { ->(b, h, p) { [b, h, p] } } before do expect(on_publish).not_to eq(on_consume) expect(on_publish).not_to be(on_consume) end it 'builds a BlockMiddleware with the provied on_publish and on_consume blocks' do subject.public_send(op, on_publish: on_publish, on_consume: on_consume) middleware = subject.middlewares.first expect(middleware).to be_an_instance_of BlockMiddleware expect(middleware.on_publish_block).to be on_publish expect(middleware.on_consume_block).to be on_consume end end end describe '#append' do it 'adds middlewares to the top of the middleware stack' do subject.append Bottom subject.append Middle subject.append Top expect(subject.middlewares).to eq [bottom, middle, top] end it_behaves_like 'a middleware builder', :append end describe '#prepend' do it 'adds middlewares to the bottom of the middleware stack' do subject.prepend Top subject.prepend Middle subject.prepend Bottom expect(subject.middlewares).to eq [bottom, middle, top] end it_behaves_like 'a middleware builder', :prepend end describe '#on_publish' do it 'passes the message data to each middleware\'s #on_publish message, bottom to top' do load_middleware_doubles expect(subject.middlewares).to eq [bottom, middle, top] allow(bottom).to receive(:on_publish).and_call_original allow(middle).to receive(:on_publish).and_call_original allow(top).to receive(:on_publish).and_call_original body = double('body') headers = double('headers') properties = double('properties') expect(subject.on_publish(body, headers, properties)).to eq [body, headers, properties] expect(bottom).to have_received(:on_publish).ordered expect(middle).to have_received(:on_publish).ordered expect(top).to have_received(:on_publish).ordered end end describe '#on_consume' do it 'passes the message data to each middleware\'s #on_consume message, top to bottom' do load_middleware_doubles expect(subject.middlewares).to eq [bottom, middle, top] allow(bottom).to receive(:on_consume).and_call_original allow(middle).to receive(:on_consume).and_call_original allow(top).to receive(:on_consume).and_call_original body = double('body') headers = double('headers') properties = double('properties') expect(subject.on_consume(body, headers, properties)).to eq [body, headers, properties] expect(top).to have_received(:on_consume).ordered expect(middle).to have_received(:on_consume).ordered expect(bottom).to have_received(:on_consume).ordered end end end end end
true
bb6f8aa0d8b85544cef4d08d71bb9a3ef68db349
Ruby
AshwiniKumar/learnstreet
/Concentration/concentration.rb
UTF-8
2,089
3.984375
4
[]
no_license
#Memory Concentration Game def populate() # This method populates the concentration game board by # populating and returning a 5x4 two-dimensional array. # Initialize all the values to zero (0), then randomly populate # numbers from 1-10 in different cells of the array, making #sure each number is only used twice. #REPLACE THIS CODE WITH YOUR populate METHOD matrix = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]; for i in 0..9 j=0 while j < 2 x = rand(5); y = rand(4); if matrix[y][x] == 0 matrix[y][x] = (i + 1) else j=j-1 end j=j+1 end end return matrix; end def selectCard(x, y) # Select the card at position (x, y). Return a card object with # values for its x & y location coordinates (i.e., [row][column]). #REPLACE THIS CODE WITH YOUR selectCard METHOD card = {} card["x"] = x card["y"] = y return card end def isMatch(selectedCard1, selectedCard2, matrix) # Given two card objects (like those created with the selectCard() # method above) and a 5x4 game board matrix of 0-9 numbers # (like the one from the populate() method above), check if the # values of the two cards are the same. Use the [x][y] coordinates # from each card object (selectedCard1 and selectedCard2) to # reference the 'matrix' values at the coordinates for each. # Compare them for a possible match. If they match, return true. # Otherwise return false. # Also make sure that selectedCard1 and selectedCard2 are not the same card! #REPLACE THIS CODE WITH YOUR isMatch METHOD if (selectedCard1['x'] != selectedCard2['x'] || selectedCard1['y'] != selectedCard2['y']) if (matrix[selectedCard1['x']][selectedCard1['y']] == matrix[selectedCard2['x']][selectedCard2['y']]) return true; end return false; end end
true
ba61719945f254ecc3a545bb0427b3322fc2c937
Ruby
jucoba/TimeTracker
/util.rb
UTF-8
501
2.78125
3
[]
no_license
require 'Win32API' class Util def self.saveToFile(filename,text) file = File.open(filename,'a') file.puts text+"\n" file.close end def self.getActiveWindowTitle() getForegroundWindow = Win32API.new('user32', 'GetForegroundWindow', [], 'L') getWindowText = Win32API.new('user32', 'GetWindowText', ['L', 'P', 'I'], 'I') window_handle = getForegroundWindow.Call() title_buffer1 = ' ' * 256 getWindowText.Call(window_handle, title_buffer1, 256) return title_buffer1 end end
true
96d1e982ef938721373b8b18c539e04ca24603a8
Ruby
kimmiies/rainforest-with-ajax
/app/controllers/sessions_controller.rb
UTF-8
987
2.65625
3
[]
no_license
class SessionsController < ApplicationController def new end #we don't have to instantiate a user object because we are only logging in, not creating new user def create user = User.find_by_email(params[:email]) #find email by email user types in if user && user.authenticate(params[:password]) #check if user exists & authenticated with password they type in session[:user_id] = user.id #session hash key value pair, # session key has been assigned redirect_to products_url, notice: "Logged in!" else flash.now[:alert] = "Invalid email or password" render "new" end end #logging in/setting hash in browser, lets server reference as user navigates through application. def destroy session[:user_id] = nil #ends the session, kills the session key & then redirects you outside the App #now current_user isnt a thing anymore you cant see certain parts of the app redirect_to products_url, notice: "Logged out!" end end
true
51f93eb5982ea3f3c5d5c272cb38586e40fd100c
Ruby
jeffwett/craigslist_scraper
/lib/craigslist_scraper/craigslist.rb
UTF-8
3,342
2.71875
3
[ "MIT" ]
permissive
require 'nokogiri' require 'open-uri' require 'cgi' require_relative 'cities' require_relative 'util' require_relative 'common' module Craigslist module Scrapers class SearchScraper include Craigslist::Cities include Craigslist::Scrapers::Common include ClassLevelInheritableAttributes inheritable_attributes :valid_fields, :data_fields, :endpoint @valid_fields = [:query, :srchType, :s, :min_price, :max_price, :sort, :postal, :search_distance, :postedToday] @data_fields = [:data_id, :datetime, :description, :url, :hood, :price] @endpoint = 'sss' ERRORS = [OpenURI::HTTPError] def valid_fields self.class.methods.grep end def _data_id(link, options) link["data-pid"] end def preprocess(options) if options[:query][:posted_today] options[:query][:postedToday] = 'T' end if options[:query][:title_only] options[:query][:srchType] = 'T' end end def search(options={}) options[:query] ||= { query: '' } preprocess(options) params = to_query(options[:query]) base_url = "https://#{options[:city]}.craigslist.org/search" uri = "#{base_url}/#{self.class.endpoint}?#{params}" puts uri begin doc = Nokogiri::HTML(open(uri)) doc.css('li.result-row').flat_map do |link| data = {} self.class.data_fields.map do |field| data[field] = self.send("_#{field}", link, options) end data end rescue *ERRORS => e [{error: "error opening city: #{options[:city]}"} ] end end def cities Cities::CITIES end def method_missing(method,*args) super unless cities.include? city ||= extract_city(method) params = { query: args.first , city: city} params.merge!(title_only: true) if /titles/ =~ method search(params) end def search_all_cities_for(query) cities.flat_map do |city| search(city: city , query: query) end end Array.class_eval do def average_price reject! { |item| item[:price] == nil } return 0 if empty? price_array.reduce(:+) / size end def median_price reject! { |item| item[:price] == nil } return 0 if empty? return first[:price].to_i if size == 1 if size.odd? price_array.sort[middle] else price_array.sort[middle - 1.. middle].reduce(:+) / 2 end end private def middle size / 2 end def price_array flat_map { |item| [item[:price]] }.map { |price| price.to_i } end end private def extract_city(method_name) if /titles/ =~ method_name method_name.to_s.gsub("search_titles_in_","").gsub("_for","") else method_name.to_s.gsub("search_","").gsub("_for","") end end def to_query(hsh) hsh.select { |k,v| self.class.valid_fields.include? k }.map {|k, v| "#{k}=#{CGI::escape v}" }.join("&") end end end end
true
90e206ebb1628af3255b4dc92a8ccb5db2fbdf7b
Ruby
diminishedprime/old-.org
/reading-list/seven_languages_in_seven_weeks/ruby/day_1_finding_a_nanny.rb
UTF-8
1,130
4.65625
5
[ "MIT" ]
permissive
# Print the string, Hello, world! (puts 'Hello, world!') # For the string "Hello, Ruby," find the index of the word "Ruby." 'Hello, Ruby'.index('Ruby') # Print your name ten times. 10.times do puts 'Your name' end # Print the string "This is sentence number 1," where the number 1 changes from # 1 to 10. 11.times do |x| puts "This is sentence number #{x}" end # Run a Ruby program from a file. (This is sorta what I'm doing right now...) # Bonus problem: If you're feeling the need for a little more, write a program # that picks a random number. Let a player guess the number, telling the player # whether the guess is too low or too high. # (Hint: rand(10) will generate a random number from 0 to 9, and gets will read # a string from the keyboard that you can translate to an integer.) def guess_a_number random_num = rand(10) guessed_correctly = false until guessed_correctly puts 'Try to guess the number!' guess = gets guess_as_number = guess.to_i if guess_as_number == random_num puts 'You guessed correctly!' guessed_correctly = true else puts 'Try again!' end end end
true
ee2aa6958c9537c937d5e1b5b85840fe7a9aaf7f
Ruby
Invoca/parameter_substitution
/spec/lib/parameter_substitution/formatters/date_time_strftime_spec.rb
UTF-8
1,307
2.8125
3
[]
no_license
# frozen_string_literal: true require_relative '../../../../lib/parameter_substitution/formatters/date_time_strftime' describe ParameterSubstitution::Formatters::DateTimeStrftime do context "Date Time Strftime formatter test" do before do @format_class = ParameterSubstitution::Formatters::DateTimeStrftime end it "have a key" do expect(@format_class.key).to eq("date_time_strftime") end it "provide a description" do expect(@format_class.description).to eq("Formats a DateTime with the provided format string.") end it "report that it has parameters" do expect(@format_class.has_parameters?).to eq(true) end it "support converting times" do example_time = Time.new(2017, 6, 8, 7, 32, 49) format1 = @format_class.new("%Y-%m-%d %H:%M:%S %:z") format2 = @format_class.new("%m/%d/%Y/%H/%M/%S") expect(format1.format(example_time)).to eq("2017-06-08 07:32:49 -07:00") expect(format1.format(example_time.to_i)).to eq("2017-06-08 07:32:49 -07:00") expect(format2.format(example_time)).to eq("06/08/2017/07/32/49") end it "not raise on invalid date" do format1 = @format_class.new("%Y-%m-%d %H:%M:%S %:z") expect(format1.format(9_999_999_999_999_999_999_999)).to eq("") end end end
true
f1cdad094b9d8c709ad46674efc82b5bf48ba8bb
Ruby
aislam2018/OO-mini-project-dumbo-web-102918
/app/models/User.rb
UTF-8
660
3.015625
3
[]
no_license
class User @@all = [] attr_accessor :name def initialize(name) @name = name @@all << self end def my_recipe_cards my_recipe_cards = RecipeCard.all.select {|card| card.user == self} end def recipes my_recipe_cards.collect { |card| card.recipe } end def add_recipe_card(date, rating, recipe) RecipeCard.new(date, rating, self, recipe) end def declare_allergen(ingredient) Allergen.new(self, ingredient) end def my_allergens Allergen.all.select {|allergen| allergen.user == self} end def allergens my_allergens.collect { |allergen| allergen.ingredient} end def self.all @@all end end
true
ee02111c73637ad26035d8376c0d1c4facf5a540
Ruby
robson3999/nurserec
/app/services/admin/medicaments/upload_csv.rb
UTF-8
1,469
2.625
3
[]
no_license
require 'csv' module Admin module Medicaments class UploadCSV attr_reader :csv, :status def initialize(params:) @csv = CSV.open(params[:file].tempfile) @status = params[:status] end def call CSV.foreach(csv.path, col_sep: ';').with_index do |row, index| next if index == 0 substance = ::Substances::Create.new(params: substance_params(row[1])).call ::Medicaments::Create.new(params: medicament_params(row, substance.id)).call end end private def substance_params(substance_name) { name: substance_name, status: status } end # postac i dawka def medicament_description(row) row_one = row[2].split(',') row_one[1..row_one.size].join(', ').strip end def medicament_params(row, substance_id) { name: row[2].split(',')[0], status: status, substance_ids: [substance_id], description: medicament_description(row), container: row[3], ean: row[4], decision_created_at: row[5], decision_period: row[6], limit_group: row[7], gov_price: row[8], gross_price: row[9], finance_limit: row[10], attachment_with_indication_name: row[11], payment_level: row[12], additional_payment: row[13] } end end end end
true
c8d482ee39c44094f30899eb76f3f3caea2786a9
Ruby
xdkernelx/personality-analyzer
/app/helpers/user_helper.rb
UTF-8
772
2.625
3
[]
no_license
helpers do def registration_errors(params) email_regex = /^[a-zA-Z0-9]+.?[a-zA-Z0-9]*@[a-zA-Z0-9]*.?[a-zA-Z0-9]*.[a-zA-Z]{2,}.?[a-zA-Z]{2,}$/ username_regex = /^[a-zA-Z0-9]{6,}$/ p params[:user]['username'] if User.find_by(email: params[:user]['email']) return "That e-mail is already taken." elsif User.find_by(username: params[:user]['username']) return "That username is already taken." elsif !email_regex.match(params[:user]['email']) return "Invalid email. Please try again." elsif params[:user]['username'].length < 7 return "Username must be at least 6 characters." elsif !username_regex.match(params[:user]['username']) return "Invalid username. Alphanumeric characters only." end end end
true
198c2ada3fd5f5f549435195859e6a0ec7c0e643
Ruby
jaredsmithse/DevBootCampWork
/phase_1/assessments/nested_arrays2.rb
UTF-8
1,259
3.875
4
[]
no_license
### Tic Tac Toe Solution ### def generate_tic_tac_toe x_or_o = ["X","O"] board_start = (0..9).to_a.map {|square| square = x_or_o[rand(x_or_o.length)]} final_board = Array.new(3) { board_start.shift(3) } end p generate_tic_tac_toe ### Convert Array Solution ### def convert_roster_format(roster) array_of_entries = [] headers = roster[0] (1..roster.size-1).each do |roster_index| array_to_be_converted = [] (roster.size - 2).times do |header_index| array_to_be_converted << [headers[header_index],roster[roster_index][header_index]] end array_of_entries << Hash[array_to_be_converted] end array_of_entries end roster = [["Number", "Name", "Position", "Points per Game"], ["12","Joe Schmo","Center",[14, 32, 7, 0, 23] ], ["9", "Ms. Buckets ", "Point Guard", [19, 0, 11, 22, 0] ], ["31", "Harvey Kay", "Shooting Guard", [0, 30, 16, 0, 25] ], ["7", "Sally Talls", "Power Forward ", [18, 29, 26, 31, 19] ], ["22", "MK DiBoux ", "Small Forward ", [11, 0, 23, 17, 0] ]] hashed_roster = convert_roster_format(roster) expected_hash_at_2 = { "Number" => "31", "Name" => "Harvey Kay", "Position" => "Shooting Guard", "Points per Game" => [0, 30, 16, 0, 25] } puts hashed_roster[2] == expected_hash_at_2 puts hashed_roster[0]["Name"] == "Joe Schmo"
true
331e2aa4efd0783210a4e605908b8be095042ab7
Ruby
baezdiazm/oo-cash-register-onl01-seng-pt-052620
/lib/cash_register.rb
UTF-8
785
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CashRegister attr_accessor :discount, :purchases, :total, :transaction def initialize(discount=0) @total = 0 @discount = discount @purchases = [] end def add_item(name, price, quantity=1) @transaction = [name, price, quantity] quantity.times do @purchases << @transaction[0] @total += @transaction[1] end end def apply_discount if discount>0 @total = @total - @total*@discount/100 result = "After the discount, the total comes to $#{@total}." else result = "There is no discount to apply." end result end def items @purchases end def void_last_transaction quantity = @transaction[2] quantity.times do @purchases.pop @total -= @transaction[1] end end end
true
5eef99a69327cb0557451d58fbf08cb629e09c03
Ruby
dmsalomon/upload
/tty.rb
UTF-8
1,660
2.984375
3
[]
no_license
# This code is 'stolen' from homebrew package manager for osx :) class Tty class << self def tick # necessary for 1.8.7 unicode handling since many installs are on 1.8.7 @tick ||= ["2714".hex].pack("U*") end def cross # necessary for 1.8.7 unicode handling since many installs are on 1.8.7 @cross ||= ["2718".hex].pack("U*") end def strip_ansi(string) string.gsub(/\033\[\d+(;\d+)*m/, "") end def blue bold 34 end def white bold 39 end def red underline 31 end def yellow underline 33 end def reset escape 0 end def em underline 39 end def green bold 32 end def gray bold 30 end def highlight bold 39 end def width `/usr/bin/tput cols`.strip.to_i end def truncate(str) str.to_s[0, width - 4] end private def color(n) escape "0;#{n}" end def bold(n) escape "1;#{n}" end def underline(n) escape "4;#{n}" end def escape(n) "\033[#{n}m" if $stdout.tty? end end end def ohai(title, *sput) title = Tty.truncate(title) if $stdout.tty? puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}" puts sput end def oh1(title) title = Tty.truncate(title) if $stdout.tty? puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}" end # Print a warning (do this rarely) def opoo(warning) $stderr.puts "#{Tty.yellow}Warning#{Tty.reset}: #{warning}" end def onoe(error) $stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}" end def odie(error) onoe error exit 1 end
true
85001a14f6cab1e0fb252312b884fd7df3476b8f
Ruby
mahendhar9/programming_problems
/csv_file_parser/csv_file_parser.rb
UTF-8
747
3.6875
4
[]
no_license
# Build a CSV File parser in Ruby that converts a CSV file to array values. # Input # csv_parser(path_to_file) # Sample Output # [ # ["Name", "Email", "City"], # ["Matt", "matt@example.com", "London"], # ["Joe", "joe@example.com", "New York"], # ["Susan", "susan@example.com", "Paris"] # ] require 'rspec' def csv_parser(file_path) File.read(file_path).split(/\n/).map {|line| line.split(',') } end # print csv_parser('data.csv') describe "CSV Parser" do it "parses a CSV file and stores each line as an array, with each column as a separate element in the array" do data = [["Name", "Email", "City"], ["Matt", "matt@example.com", "London"], ["Joe", "joe@example.com", "New York"], ["Susan", "susan@example.com", "Paris"]] expect(csv_parser('data.csv')).to eq(data) end end
true
7578739a64a88f506442259284e592671fccba39
Ruby
eyeced/ruby_problems
/src/radix_sort.rb
UTF-8
592
3.5625
4
[ "MIT" ]
permissive
class RadixSort def self.sort(arr) max = arr.max max.to_s.length.times do |i| # initialize bucket buckets = Array.new(20){[]} # defining the base for each loop to get the digit at that base increasing it after each loop bar = 10 ** i arr.each do |x| d = get_digit_at(x, bar) d += bar if x >= 0 buckets[d] << x end arr = buckets.flatten end arr end # get the digit def self.get_digit_at(num, base) (num / base) % 10 end p sort([2, 5, 1, 9, 8, 3, 4, -87, -47, -51, 57, 33, 34, 27, 91, 84]) end
true
de56b4d119ee39f5a11d0cb1d23be10b766e7de9
Ruby
yumojin/Example-Sketches
/samples/contributed/grapher.rb
UTF-8
880
2.90625
3
[ "MIT" ]
permissive
# Grapher is based on a context free art design # by ColorMeImpressed (takes a bit of time to run) # http://www.contextfreeart.org/gallery/view.php?id=2844 # load_library :fastmath CMIN = -2.0 # Important to specify float else get random int from range? CMAX = 2.0 FUZZ = 0.04 SZ = 5 def setup size 600, 600 no_stroke color_mode(HSB, 1.0) background(0) frame_rate(4_000) end def draw translate(width / 2, height / 2) dot(rand(-180..180), rand(-180..180), rand(CMIN..CMAX)) unless frame_count > 200_000 end def dot(px, py, c) func = DegLut.sin(px) + DegLut.sin(py) + c # change function to change the graph eg. # func = DegLut.cos(px) + DegLut.sin(py) + c if func.abs <= FUZZ fill(((CMIN - c) / (CMIN - CMAX)), 1, 1) ellipse px * width / 360, py * height / 360, SZ, SZ else dot(rand(-180..180), rand(-180..180), rand(CMIN..CMAX)) end end
true
4b9bdff6bebe1006c9124be07b4b52e77d230d11
Ruby
shirleytang0121/AAClasswork
/W2D4/shirley_tang_recap_exercise_3/general_problems/longest_streak.rb
UTF-8
599
3.734375
4
[]
no_license
def longest_streak(str) streak=str[0] count=1 max_length=1 (0...str.length-1).each do |i| if str[i]==str[i+1] count+=1 if count>=max_length max_length=count streak=str[i] end else count=1 end end return streak*max_length end p longest_streak('a') # => 'a' p longest_streak('accccbbb') # => 'cccc' p longest_streak('aaaxyyyyyzz') # => 'yyyyy p longest_streak('aaabbb') # => 'bbb' p longest_streak('abc') # => 'c'
true
918d5a34fb22f901e17fe27d68da3a5782b645f4
Ruby
seidmanmb/ruby-all
/ruby/meanboss.rb
UTF-8
131
2.859375
3
[]
no_license
puts '' puts 'WHAT DO YOU WANT?' puts '' want = gets.chomp puts '' puts 'WHAT DO YOU MEAN "' + want.upcase + '"?!? YOU\'RE FIRED!!'
true
0ea809f0dfbb2673c1f5e2d8b68c3a7dff0a7c0a
Ruby
connorpaulstauffer/app-academy
/prep-work/test-first-ruby/lib/03_simon_says.rb
UTF-8
472
4.03125
4
[]
no_license
def echo message message end def shout message message.upcase end def repeat message, num = 2 ("#{message} " * num).chop end def start_of_word string, num string[0..(num - 1)] end def first_word string string.split[0] end def titleize string little_words = ["and", "the", "is", "a", "over"] string.split.map.with_index do |word, idx| if idx == 0 || !little_words.include?(word) word.capitalize else word end end.join(" ") end
true
2b198d3c98eba079fe7189c6fa46463c3db69690
Ruby
HatemC/ruby_practice
/can_i_vote.rb
UTF-8
276
3.265625
3
[]
no_license
require_relative "vote_test" puts "What is your first name" first_Name = gets.chomp puts "What is your last name" last_Name = gets.chomp puts 'What is your age' age = gets.chomp.to_i name=fullName(first_Name,last_Name) ageTested=voteAge(age) puts "#{name}, #{ageTested}"
true
bdcbfd1a93ab477b043bf8a231989578008d69ba
Ruby
KOBA789/internet-sampler
/main.rb
UTF-8
3,510
2.53125
3
[ "CC-BY-4.0" ]
permissive
# -*- coding: utf-8 -*- require 'bundler/setup' require 'json' require 'sinatra' require 'sinatra/reloader' if development? require 'sinatra-websocket' require 'redis' require 'slim' class Time def msec self.instance_eval { self.to_i * 1000 + (usec/1000) } end end class Subscriber attr_reader :subscribers def initialize @subscribers = [] end def add ws @subscribers << ws end def delete ws @subscribers.delete ws end def send ws, message ws.send message end def broadcast message @subscribers.each do |sub| sub.send message end end def count @subscribers.size end end class Sampler def initialize tracks, redis @tracks = tracks @redis = redis end def has_track? slug @tracks.select do |track| track[:slug] == slug end.size == 1 end def get_count slug @redis.get slug if has_track? slug end def incr slug @redis.incr slug if has_track? slug end def tracks @tracks.map do |track| track[:count] = @redis.get track[:slug] track end end def track_info slug t = @tracks.select do |track| track[:slug] == slug end.first t[:count] = @redis.get slug t end end class InternetSampler def initialize subscribers, sampler @sub = subscribers @sampler = sampler end def play slug, msec if @sampler.has_track? slug i = @sampler.incr slug EM.next_tick do @sub.broadcast({ type: :play, count: i, slug: slug, msec: msec }.to_json) end else puts :err end end def add ws @sub.add ws end def delete ws @sub.delete ws end def update_subscribers_count @sub.broadcast({ type: :num, count: @sub.count, }.to_json) end def tracks @sampler.tracks end def track_info slug @sampler.track_info slug end end configure do set :server, 'thin' set :ws_url, ENV["WS_URL"] set :is, InternetSampler.new( Subscriber.new, Sampler.new( [ { slug: "エモい", path: "/mp3/emoi.mp3", description: "" }, { slug: "最高", path: "/mp3/saiko.mp3", description: "" }, { slug: "銅鑼", path: "/mp3/Gong-266566.mp3", description: "" }, { slug: "Frontliner", path: "/mp3/frontliner-fsharp-kick.mp3", description: "" } ], Redis.new(host: "127.0.0.1", port:"6379") ) ) end get '/' do unless request.websocket? @ws_url = (settings.ws_url || "ws://#{request.env['HTTP_HOST']}/") @tracks = settings.is.tracks slim :index else request.websocket do |ws| ws.onopen do settings.is.add ws ws.send({ type: :msg, msg: "WebSocket connected!" }.to_json) settings.is.update_subscribers_count end ws.onmessage do |msg| m = JSON.parse msg settings.is.play m['slug'], m['msec'] end ws.onclose do warn("WebSocket closed") settings.is.delete ws settings.is.update_subscribers_count end end end end get '/api/v1/tracks' do content_type 'application/json' settings.is.tracks.to_json end get '/api/v1/tracks/:slug/play' do content_type 'application/json' settings.is.play params[:slug] settings.is.track_info(params[:slug]).to_json end
true
3106a2c370dc28c348181df4504612b584203b4c
Ruby
onelang/TestArtifacts
/CompilationTest/BigInteger/results/BigInteger.rb
UTF-8
580
3.765625
4
[ "MIT" ]
permissive
class MathUtils def self.calc(n) result = 1 i = 2 while i <= n result = result * i if result > 10 result = result >> 2 end i += 1 end return result end def self.calc_big(n) result = 1 i = 2 while i <= n result = result * i + 123 result = result + result if result > 10 result = result >> 2 end i += 1 end return result end end puts "5 -> #{MathUtils.calc(5)}, 24 -> #{MathUtils.calc_big(24)}"
true
b054e9ce461d0c1a5a0291e0e3ed39b47217e43b
Ruby
d3z/product-import_export
/default_file_handler.rb
UTF-8
362
3.28125
3
[]
no_license
# Simple file handler that reads contents of # file to string and writes string straight # to file class DefaultFileHandler def read_data_from(filename) file = File.open(filename, "r") file.read end def write_data_to(filename, data) File.open(filename, "w") { |file| file.write(data) } end end
true
8365950d1880bccf90b573cf90236331f4399490
Ruby
mobolaji89/phase-0-tracks
/ruby/gps2_2.rb
UTF-8
5,755
4.09375
4
[]
no_license
#gps 2.2 #Pseudocode # Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # Split string on " " = array # create a hash # set default quantity = 1 # iterate through array of items # for each item add to hash # print the list to the console (print_list method) # output: Hash. Key = Item, value = quantity (int) # Method to add an item to a list # input: item list, item name and optional quantity # steps: add item to list with key = item name and quantity = quantity parameter if present, otherwise default # output: hash with new item added # Method to remove an item from the list # input: item list, item name (key) # steps: iterate through item list hash and remove items with keys matching input item key # output: hash with item removed # Method to update the quantity of an item # input: item list, item, new quantity # steps: update input key with input new value # output: updated item list hash # Method to print a list and make it look pretty # input: item list # steps: iterate through hash and print each key and value separated by ':', one pair per line # output: nil #str = "carrots apples cereal pizza" # Method to create a list def create_list (list) arr = list.split(' ') grocery_list = Hash.new arr.each do |key| grocery_list[key] = 1 end grocery_list end # Method to add an item to a list def add_item (list, item, quantity = 1) list[item] = quantity list end # Method to remove an item from the list def remove_item (list, item) list.delete(item) list end # Method to update the quantity of an item def update_quantity(list, item, quantity) list[item] = quantity list end # Method to print a list and make it look pretty def print_list(list) list.each do |key, value| puts "#{key.capitalize}, #{value}" end end #create list test_list = create_list("") =begin p add_item(test_list, "lemonade", 2) p add_item(test_list, "tomatoes", 3) p add_item(test_list, "onions", 1) p add_item(test_list, "ice cream", 4) =end #create an array for each item and each item's quantity test_items = ["lemonade", "tomatoes", "onions", "ice cream"] test_quantities =[2, 3, 1, 4] #adding items to empty hash (test_list) index = 0 while index < test_items.length do add_item(test_list, test_items[index], test_quantities[index]) index += 1 end #remove lemonade from list remove_item(test_list, "lemonade") #update quantity of ice cream to 1 update_quantity(test_list, "ice cream", 1) #print out your list print_list(test_list) =begin #Coyotes 2016 # Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # Create an empty hash # Empty array of string input # Split each element into separate strings # Each string will be stored as a key in the hash # set default quantity(set equal to 1) def create_list(val) grocery_list = {} val.split(' ').map{|x| grocery_list[x.to_sym] =1} grocery_list end # Method to add an item to a list # input: Takes list and new item to add # steps: New item is assigned to grocery_list and default a quantity of 1 # output: New item was "milk" and it returned milk with the default qty def add_item(grocery_list, item) grocery_list[item.to_sym] = 1 end # Method to remove an item from the list # input: Takes list and item that needs to be removed # steps: grocery_list is updated by matching matching the item given as an argument to an existing key, and using a delete method # output: Returns updated list def del_item(grocery_list, item) grocery_list = grocery_list.delete_if {|key, value| key == item.to_sym} end # Method to update the quantity of an item # input: Takes list, item desired, qty desired # steps: update quantity by accessing key desired and setting equal to new quantity passed as argument # output: returning updated list. def quantity_update(grocery_list, item, quantity) grocery_list[item.to_sym] = quantity #return grocery_list end # Method to print a list and make it look pretty # input:Inputting create list methond due to it returning grocery_list hash # steps: iterate through the hash using the .each method, printing the key and value for each item. # output: A list of groceries outputted def print_list(grocery_list) grocery_list.each {|item, quantity| puts "#{item.capitalize}, Qty: #{quantity}" } end # USER INTERFACE puts "Please enter what items you wish to add to your list (or enter done)" items = gets.chomp u_list = create_list(items) puts "\nYour list so far" puts print_list(create_list(items)) loop do puts "-------------------------------------------------" puts "\nEnter the what you would like to do to your list? ('add' item, 'delete' item, 'update' quantity or just enter 'done'):\n" update = gets.chomp break if update.downcase == "done" if update.downcase == "add" puts "What would you like to add to your list?" add = gets.chomp add_item(u_list, add) p print_list(u_list) elsif update.downcase == "delete" puts "What would you like to delete from your list?" rem = gets.chomp del_item(u_list, rem) p print_list(u_list) elsif update.downcase == "update" puts "What item would you like to update the quantity to?" item = gets.chomp puts "What is your new quantity update for #{item}?" qty = gets.chomp.to_i quantity_update(u_list,item, qty) p print_list(u_list) else puts "I don't understand please enter the correct option" end end print_list(u_list) =end
true
90fe2fa51bb5b169f3a419b41790d61d32ada31a
Ruby
Richard-Pentecost/cruise_ships
/spec/ship_spec.rb
UTF-8
1,358
2.96875
3
[]
no_license
require_relative '../ship' require_relative '../port' require_relative '../itinerary' describe Ship do before(:each) do @dover = Port.new('Dover') @calais = Port.new('Calais') itinerary = Itinerary.new([@dover, @calais]) @ship = described_class.new(itinerary) end context 'ship' do it 'initiates a ship with a starting port' do expect(@ship.current_port).to be(@dover) end it 'gets added to a port on instantiation' do expect(@dover.ships).to include(@ship) end it 'initiates a ship with a previous port of nil' do expect(@ship.previous_port).to eq(nil) end it 'can set sail' do @ship.set_sail expect(@ship.previous_port).to be(@dover) expect(@ship.current_port).to eq('') expect(@dover.ships).to_not include(@ship) end it 'can dock at a different port' do @ship.set_sail @ship.dock expect(@ship.current_port).to be(@calais) expect(@calais.ships).to include(@ship) end it "can't sail further than it's last port in the itinerary" do # dover = Port.new('Dover') # calais = Port.new('Calais') # itinerary = Itinerary.new([dover, calais]) # ship = described_class.new(itinerary) @ship.set_sail @ship.dock expect{ @ship.set_sail }.to raise_error(Exception) end end end
true
f7b486567fc00353c7442533cde194af10be2037
Ruby
RANA-AKBAR/Karaoke_Bar
/guest.rb
UTF-8
312
3.140625
3
[]
no_license
class Guest attr_accessor :name, :money, :fav_song def initialize(name, money, fav_song) @name = name @money = money @fav_song = fav_song end def charge(amount) return @money -= amount end def customer_can_afford_drink(drinks_hash, drink) return @money <= drinks_hash[drink][:info].price end end
true
68a4725126bcfd4f7dcd91db1d3c01c4493fae62
Ruby
JRRS1982/TechTests
/bowling/bowling-scorecard/spec/game_spec.rb
UTF-8
3,616
3.453125
3
[]
no_license
require 'Game' require 'pry' describe 'Game' do context '.roll' do it 'increments the score when pins are knocked down' do my_game = Game.new my_game.roll(1) expect(my_game.score).to eq(1) end end context '.frame' do it 'up when a ten is rolled' do my_game = Game.new my_game.roll(10) expect(my_game.frame).to eq(2) end it 'up after two balls' do my_game = Game.new my_game.roll(3) my_game.roll(7) expect(my_game.frame).to eq(2) end end context '.over?' do it '20 gutter balls' do my_game = Game.new 20.times { my_game.roll(0) } expect(my_game.over?).to be(true) end it 'not at the start' do my_game = Game.new expect(my_game.over?).to be(false) end end context '.a_strike?' do it 'strike is' do my_game = Game.new my_game.roll(10) expect(my_game.a_strike?(my_game.score_array[0])).to be(true) end it "strike isn't" do my_game = Game.new my_game.roll(4) expect(my_game.a_strike?(my_game.score_array[0])).to be(false) end end context '.a_spare?' do it 'spare is' do my_game = Game.new my_game.roll(3) my_game.roll(7) expect(my_game.a_spare?(my_game.score_array[0])).to be(true) end it "spare isn't" do my_game = Game.new my_game.roll(3) my_game.roll(2) expect(my_game.a_spare?(my_game.score_array[0])).to be(false) end end context '.spare_bonus' do it 'spares' do my_game = Game.new my_game.roll(2) my_game.roll(8) my_game.roll(5) expect(my_game.score).to be(20) end it 'different spare' do my_game = Game.new my_game.roll(2) my_game.roll(8) my_game.roll(3) expect(my_game.score).to be(16) end it 'a different frame' do my_game = Game.new 4.times { my_game.roll(1) } my_game.roll(2) my_game.roll(8) my_game.roll(5) expect(my_game.score).to eq(24) end end context '.strike_bonus' do it 'a strike' do my_game = Game.new my_game.roll(10) my_game.roll(2) my_game.roll(3) my_game.roll(1) expect(my_game.score).to eq(21) end it 'double strike' do my_game = Game.new my_game.roll(10) my_game.roll(10) 16.times { my_game.roll(0) } expect(my_game.score).to eq(30) end it 'triple strike' do my_game = Game.new my_game.roll(10) my_game.roll(10) my_game.roll(10) 14.times { my_game.roll(0) } expect(my_game.score).to eq(60) end it 'variable strike 1' do my_game = Game.new my_game.roll(2) my_game.roll(1) my_game.roll(10) my_game.roll(5) my_game.roll(4) 14.times { my_game.roll(0) } expect(my_game.score).to eq(31) end it 'variable strike 2' do my_game = Game.new my_game.roll(2) my_game.roll(0) my_game.roll(10) my_game.roll(10) 14.times { my_game.roll(0) } expect(my_game.score).to eq(32) end end context '.score' do it 'zero score' do my_game = Game.new 20.times { my_game.roll(0) } expect(my_game.score).to eq(0) end it '1 each time' do my_game = Game.new 20.times { my_game.roll(1) } expect(my_game.score).to eq(20) end end context '.statement' do it 'prints out a heading' do my_game = Game.new expect(my_game.statement).to include('Frame || Roll 1 || Roll 2 || Frame Score || Total') end end end
true
cc5827b33d724242ef3db3fba642268851b059ac
Ruby
rikitoro/design_patterns_in_ruby
/sec13_Factory/habitat_test/algae.rb
UTF-8
132
3.484375
3
[]
no_license
class Algae def initialize(name) @name = name end def grow puts("藻#{@name}は日光を浴びて育ちます。") end end
true
7e5b0b0277cc32043b6be8d34cd95d7a28585d13
Ruby
IIIIIIIIll/RubyQuizess
/Quiz12/question10.rb
UTF-8
247
3.015625
3
[]
no_license
class Book def initialize(args) @pages = args.fetch(:pages) @title = args.fetch(:title) end end class Textbook < Book def initialize(args) @chapters = args.fetch(:chapters) end end p textbook = Textbook.new({ chapters: 20 })
true
4d4db864bd315a9fabc94d3e4d6b972068ccc876
Ruby
yourpromotioncode/Numbers
/day8-2.rb
UTF-8
346
2.8125
3
[]
no_license
puts("[Please enter your ID] \n") input_id = gets.chomp() # Master_chief = "mc11" # Dream_Theater = "dt2002" ids = ['mc11' , 'dt2002'] # if Master_chief == in_str # elif Dream_Theater ==in_str: for id in ids do if id == input_id puts("** " + id + "!! Welcome to ITW database hub") exit end end puts("** Invalid ID **")
true
5e1ae8d3de4795c844318458db29a23a9f560e0d
Ruby
EGI-FCTF/rOCCI-core
/lib/occi/core/parsers/json/action_instance.rb
UTF-8
1,664
2.515625
3
[ "Apache-2.0" ]
permissive
module Occi module Core module Parsers module Json # Static parsing class responsible for extracting action instances from JSON. # Class supports 'application/json' via `json`. No other formats are supported. # # @author Boris Parak <parak@cesnet.cz> class ActionInstance include Yell::Loggable include Helpers::ErrorHandler extend Helpers::RawJsonParser class << self # Shortcuts to interesting methods on logger DELEGATED = %i[debug? info? warn? error? fatal?].freeze delegate(*DELEGATED, to: :logger, prefix: true) # Parses action instances. Internal references between objects are converted from strings # to actual objects. Actions have to be declared in the provided model. # # @param body [String] JSON body for parsing # @param model [Occi::Core::Model] model with existing categories # @return [Occi::Core::ActionInstance] action instance def json(body, model) parsed = raw_hash(body) action = handle(Occi::Core::Errors::ParsingError) { model.find_by_identifier! parsed[:action] } logger.debug "Identified #{action.class}[#{action.identifier}]" ai = Occi::Core::ActionInstance.new(action: action) ep = Entity.new(model: model) ep.set_attributes!(ai, parsed[:attributes]) if parsed[:attributes] logger.debug "Parsed into ActionInstance #{ai.inspect}" if logger_debug? ai end end end end end end end
true
bb9d962d98bc90af2a55c3c3daf90c3023ded53d
Ruby
manuelguillegil/Examen3
/P3-Pregunta1.1.rb
UTF-8
1,067
3.296875
3
[]
no_license
## MANUEL GUILLERMO GIL 14-10397 class Secuencia def empty raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end def add raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end def remove raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end end class Pila < Secuencia attr_accessor :elements def initialize(elements) @elements = [] elements.each {|element| self.add(element)} end def empty return @elements.empty? end def add(elemento) @elements << elemento end def remove return @elements.pop end end class Cola < Secuencia attr_accessor :elements def initialize(elements) @elements = [] elements.each {|element| self.add(element)} end def empty return @elements.empty? end def add(elemento) @elements.insert(0,elemento) end def remove return @elements.pop end end
true
dfe89fb4d827174da10f5b95594f6abe0598a857
Ruby
UrsaDK/imdb-search
/api/tasks/models/title_basics.rb
UTF-8
1,935
2.921875
3
[]
no_license
# frozen_string_literal: true module Task module Model module TitleBasics class << self # @yeild [formatted_line] Executes block for each line of the file. # @yieldparam data [Hash] A hash of the line, with column headers as keys, # and values as they are returned by Formatter. def each_line(file) content = Task::Datasource::Tsv.new(file) content.formatter = TitleBasics::Formatter content.each_line do |data| yield(data) if block_given? end end def total_records(file) count = -1 # The first line is the header, not a record content = Task::Datasource::Tsv.new(file) content.source.each_line { count += 1 } count.negative? ? 0 : count end end module Formatter class << self def sanitize(value) value = value.to_s.strip return nil if value == '\N' value end def normalize(value) return nil unless (value = sanitize(value)) value.downcase end def to_integer(value) return nil unless (value = sanitize(value)) value.to_i end def to_boolean(value) return nil unless (value = to_integer(value)) !value.zero? end def to_normalized_array(value) return nil unless (value = sanitize(value)) value.split(',').map { |v| v.strip.downcase.capitalize } end alias titleType normalize alias primaryTitle sanitize alias originalTitle sanitize alias startYear to_integer alias endYear to_integer alias runtimeMinutes to_integer alias isAdult to_boolean alias genres to_normalized_array end end end end end
true
853c1ba6bf00da36e06440559114273846307fe1
Ruby
bellef/getaround_backend_application
/level1/spec/rental_spec.rb
UTF-8
571
2.890625
3
[]
no_license
require_relative '../rental' require_relative '../car' describe Rental do describe '#price' do context 'with a car costing 20€ a day and 10 cents a km' do let(:car) { Car.new(**{ id: 1, price_per_day: 2000, price_per_km: 10}) } context 'with a rental lasting 3 days and driving 100km' do let(:rental) do Rental.new(car, **{ id: 1, car_id: 1, start_date: "2017-12-8", end_date: "2017-12-10", distance: 100 }) end it 'costs 70€' do expect(rental.price).to eq(7000) end end end end end
true
42bb239aff19ad167a1b99eec9b9e7264da5f457
Ruby
kikicat-meows/aA_Classwork
/W4D2/chess/board_components/board.rb
UTF-8
1,055
3.671875
4
[]
no_license
require_relative "piece" class Board def initialize black_back_row = [Array.new(8) {Piece.new}] black_front_row = [Array.new(8) {Piece.new}] empty_space = Array.new(4) {Array.new(8) {nil} } ### PH for NullPiece white_front_row = [Array.new(8) {Piece.new}] white_back_row = [Array.new(8) {Piece.new}] @board = black_back_row + black_front_row + empty_space + white_front_row + white_back_row end attr_reader :board def [](pos) row, col = pos board[row][col] end def []=(pos, val) row, col = pos board[row][col] = val end def move_piece(start_pos, end_pos) raise "Start position not on board, please check your input" if !valid_pos?(start_pos) raise "Target position invalid, please check your input again" if !valid_pos?(end_pos) raise "There is no piece at start_pos" if self[start_pos] == nil ### PH for NullPiece self[end_pos], self[start_pos] = self[start_pos], nil ### PH for NullPiece end def valid_pos?(pos) pos.all? { |coord| coord.between?(0, 7) } end end
true
2f57a317722de2d24a2cac9c4687bed99015cbd8
Ruby
gorodish/all_files
/week_10/day_3/ruby_test/race.rb
UTF-8
164
3.421875
3
[]
no_license
def increment(num) num + 1 end sum = 0 threads = (1..10).map do Thread.new do 100000.times {sum = increment(sum)} end end threads.each(&:join) puts sum
true
c62480fd589ff7ba54cea4708d0ed57063c5ae44
Ruby
samuelgustave/learn_to_program_chis_pine
/chap01/ex01.rb
UTF-8
670
4.6875
5
[]
no_license
# ex01.rb # how many hours are in a year hours_in_a_years = 365 * 24 puts "The are #{hours_in_a_years} hours in a year!" # how many minutes are in a decade ? minutes_in_a_decade = 10 * 365 * 24 * 60 puts "The are #{minutes_in_a_decade} minutes in a decade!" # how many seconds old are you? seconds_old = 36 * 365 * 24 * 60 * 60 puts "I am #{seconds_old} seconds old!" # how many chocolats do you hope to eat in your life? number_chocolate_in_lifetime = 100 * 365 puts "I hope to eat up to #{number_chocolate_in_lifetime} chocolats in my lifetime!" # if I am 1230 million seconds old, how old am I? age = 1230000000 / 60 / 60 / 24 / 365 puts "I am #{age} years old!"
true
b67833288731542e7c6461fbf24531c3954d6365
Ruby
aristides1000/Ruby_Practices
/Methods/example_methods.rb
UTF-8
7,741
4.25
4
[ "CC0-1.0" ]
permissive
=begin p "anything".reverse =end # Estows dos códigos hacen lo mismo porque puts es un método y en ruby los Métodos pueden ir entre parentesis o sin ellos =begin puts "anything" puts("anything") =end # Con la palabra def realizo la declaración de nuevos métodos =begin def my_name "Joe Smith" end puts my_name =end # Nombres de métodos válidos y no válidos en Ruby =begin method_name # valid _name_of_method # valid 1_method_name # invalid method_27 # valid method?_name # invalid method_name! # valid begin # invalid (Ruby reserved word) begin_count # valid =end =begin def greet(name) "Hello, " + name + "!" end puts greet("John") =end # Aquí name es un parámetro y John es un argumento # los parámetros actúan como variables de marcador de posición en la plantilla de su método, mientras que los argumentos son las variables reales que se pasan al método cuando se llama. # Ejemplo de parámetros predeterminaods o Default Parameters =begin def greet(name = "stranger") "Hello, " + name + "!" end puts greet("Jane") #=> Hello, Jane! puts greet #=> Hello, stranger! =end =begin def my_name "Joe Smith" end puts my_name #=> "Joe Smith" =end # la palabra clave return es un retorno explícito o un explicit return y le dice a nuestro método lo que va a retornar =begin def my_name return "Joe Smith" end puts my_name #=> "Joe Smith" =end # en Ruby, existen retornos implícitos y pocos lenguajes los permiten =begin def even_odd(number) if number % 2 == 0 "That is an even number." else "That is an odd number." end end puts even_odd(16) #=> That is an even number. puts even_odd(17) #=> That is an odd number. =end =begin def my_name return "Joe Smith" "Jane Doe" end puts my_name #=> "Joe Smith" =end =begin def even_odd(number) unless number.is_a? Numeric return "A number was not entered." end if number % 2 == 0 "That is an even number." else "That is an odd number." end end puts even_odd(20) #=> That is an even number. puts even_odd("Ruby") #=> A number was not entered. =end # Si quito la palabra clave return de mi método no voy a obtener lo que esperaba =begin def even_odd(number) unless number.is_a? Numeric "A number was not entered." end if number % 2 == 0 "That is an even number." else "That is an odd number." end end puts even_odd(20) #=> That is an even number. puts even_odd("Ruby") #=> A number was not entered. =end # Este método retorna nil =begin def puts_squared(number) puts number * number end puts_squared(8) =end #En cambio este método retorna un número =begin def return_squared(number) number * number end return_squared(6) =end =begin def return_squared(number) number * number end # return_squared(6) x = return_squared(20) #=> 400 y = 100 sum = x + y #=> 500 puts "The sum of #{x} and #{y} is #{sum}." #=> The sum of 400 and 100 is 500. =end # encadenar métodos o Chaining Methods =begin phrase = ["be", "to", "not", "or", "be", "to"] puts phrase.reverse.join(" ").capitalize #=> "To be or not to be" =end # Este método anterior tiene como resultado lo siguiente por pasos # ["be", "to", "not", "or", "be", "to"].reverse # = ["to", "be", "or", "not", "to", "be"].join(" ") # = "to be or not to be".capitalize # = "To be or not to be" # Los Métodos de Predicado o Predicate Methods son aquellos métodos que terminan en "?" y retornan true or false osea un valor booleano =begin puts 5.even? #=> false puts 6.even? #=> true puts 17.odd? #=> true puts 12.between?(10, 15) #=> true =end # yo puedo crear mis PROPIOS MÉTODOS con un "?" para indicar que el método devuelve un valor booleano =begin whisper = "HELLO EVERYBODY" puts whisper.downcase #=> "hello everybody" puts whisper #=> "HELLO EVERYBODY" =end # Si deseamos sobrescribir los métodos o las variables debemos usar el método bang !, OJO Este método no es recomendable OJO # La mejor forma de hacerlo, es crear una nueva variable con la información que deseamos almacenar # Escribir whisper.downcase!es el equivalente a escribir whisper = whisper.downcase. # parámetros predeterminados =begin def say(words = 'hello') puts words + "." end say() say("hi") say("how are you") say("I'm fine") =end =begin a = 5 def some_method a = 3 end puts a =end =begin [1, 2, 3].each do |num| puts num end =end =begin def print_num(num) puts num end print_num(4) =end =begin def some_method(number) number = 7 end a = 5 some_method(a) puts a =end =begin a = [1, 2, 3] # Example of a method definition that modifies its argument permanently def mutate(array) array.pop end p "Before mutate method: #{a}" mutate(a) p "After mutate method: #{a}" =end =begin a = [1, 2, 3] # Example of a method definition that does not mutate the caller def no_mutate(array) array.last end p "Before no_mutate method: #{a}" no_mutate(a) p "After no_mutate method: #{a}" =end =begin a = [1, 2, 3] def mutate(array) array.pop end p "Before mutate method: #{a}" p mutate(a) p "After mutate method: #{a}" =end =begin def add_three(number) number + 3 end returned_value = add_three(4) puts returned_value =end =begin def add_three(number) return number + 3 end returned_value = add_three(4) puts returned_value =end =begin def add_three(number) number + 3 number + 4 end returned_value = add_three(4) puts returned_value =end =begin def just_assignment(number) foo = number + 3 end just_assignment(2) =end =begin def add_three(n) n + 3 end # add_three(5) add_three(5).times { puts 'this should print 8 times' } =end =begin "hi there".length.to_s =end # Este método no funcionará porque estamos usando puts # no funciona con puts pero si funciona con p o sin colocar ninguno de los dos, esto se debe a los valores de retorno que generamos # no funciona por el puts =begin def add_three(n) puts n + 3 end add_three(5).times { puts "will this work?" } =end # si funciona con el p =begin def add_three(n) puts n + 3 end add_three(5).times { puts "will this work?" } =end # funciona aunque no le coloquemos nada =begin def add_three(n) puts n + 3 end add_three(5).times { puts "will this work?" } =end # Esta sería una de las formas de en las que podemos usar puts sin que nos de un error de retorno =begin def add_three(n) new_value = n + 3 puts new_value new_value end add_three(5).times { puts "will this work?" } =end =begin def add(a, b) a + b end def subtract(a, b) a - b end add(20, 45) subtract(80, 10) =end =begin def add(a, b) a + b end def subtract(a, b) a - b end def multiply(num1, num2) num1 * num2 end multiply(add(20, 45), subtract(80, 10)) =end =begin def add(a, b) a + b end def subtract(a, b) a - b end def multiply(num1, num2) num1 * num2 end add(subtract(80, 10), multiply(subtract(20, 6), add(30, 5))) =end # esta es la famosa pila de llamada o pila o stack o call Stack =begin def first puts "first method" end def second first puts "second method" end second puts "main method" =end # el print y el puts retornan o return nil # alcances de las variables # este ejemplo va a dar error por el alcance de las variables =begin def add_two(number) number + 2 end puts add_two(3) puts number =end =begin def add_one(number) number + 1 end def add_two(number) number = add_one(number) add_one(number) end puts add_two(3) =end =begin def sum(number, other) number + other end def add_one(number) sum(number, 1) end def add_two(number) sum(number, 2) end puts add_one(3) puts add_two(3) =end #El uso del .inspect =begin puts 5.inspect puts "A string".inspect puts [1, 2, 3].inspect =end =begin def p(object) puts object.inspect end p("Hola") =end
true
b33b5f279510316ae45fee38b891b683d294cbfe
Ruby
devinpile/summer-field-6995
/spec/features/movies/show_spec.rb
UTF-8
1,968
2.578125
3
[]
no_license
require 'rails_helper' RSpec.describe 'Movies Show Page' do before do @studio1 = Studio.create!(name: "Syntax Studios", location: "Burbank") @movie1 = @studio1.movies.create!(title: "Active Record", creation_year: 2022, genre: "Suspense/Thriller") # @movie2 = @studio1.movies.create!(title: "Add Foreign Key", creation_year: 2022, genre: "Romantic/Comedy") @actor1 = Actor.create!(name: "Ruby Rails", age: 27) @actor2 = Actor.create!(name: "Mercy Quill", age: 53) @actor3 = Actor.create!(name: "Repo Pomodoro", age: 33) @movie_actor = MovieActor.create!(movie_id: @movie1.id, actor_id:@actor1.id) @movie_actor = MovieActor.create!(movie_id: @movie1.id, actor_id:@actor2.id) # @movie_actor = MovieActor.create!(movie_id: @movie2.id, actor_id:@actor1.id) # @movie_actor = MovieActor.create!(movie_id: @movie2.id, actor_id:@actor3.id) visit movie_path end it 'shows movie title, creation year, and genre' do expect(page).to have_content(@movie1.title) expect(page).to have_content(@movie1.creation_year) expect(page).to have_content(@movie1.genre) end it 'lists all actors from younest to oldest' do expect(@actor1).to appear_before(@actor2) end it 'i see the average age of all of the movies actors' do expect(page).to have_content("Average Actor Age: #{@actors.average_age}") end describe 'add an actor to a movie' do it 'i do not see any actor listed that are not part of the movie' do expect(page).to_not have_content(@actor3) end it 'i see a form to add an actor to this movie' do expect(page).to have_content("Add an Actor:") end it 'when i fill out the form and click submit, i am redirected to movie show page and see the actor added' do fill_in "Name", with: "Alan Turing" fill_in "Age", with: 55 click_on "Submit" expect(current_path).to eq("/movies/#{@movie1.id}") expect(page).to have_content("Alan Turing") end end end
true
f75d721b4c9080790edad4f47a5f981e0b34d616
Ruby
unasuke/AtCoder
/Regular/12/12-A.rb
UTF-8
309
3.578125
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#AtCoder Regular 12 A week = STDIN.gets.chomp if week == "Sunday" || week == "Saturday" then puts "0" elsif week == "Monday" then puts "5" elsif week == "Tuesday" then puts "4" elsif week == "Wednesday" then puts "3" elsif week == "Thursday" then puts "2" elsif week == "Friday" then puts "1" end
true
4ac4b7cb42fe973a78a839739927e1a26ef417f8
Ruby
sarah-mosbah/DataStructuresInRuby
/polytree.rb
UTF-8
1,057
3.6875
4
[]
no_license
class PolyTreeNode attr_accessor :parent, :children, :value def initialize(value) @value=value @parent=nil @children=[] end def parent=(value) return if @parent==value @parent.children.reject! {|node| node==self} unless @parent.nil? @parent=value @parent.children.push(self) unless @parent.nil? self end def add_child(child_node) child_node.parent=self end def remove_child(child_node) child_node.parent=nil self.children.reject! {|node| node==child_node} end def dfs(target_value) return self if target_value==self.value self.children.each do |child| search_result=child.dfs(target_value) return search_result unless search_result.nil? end nil end def bfs(target_value) queue=[self] until queue.empty? el=queue.shift return el if target_value== el.value el.children.each {|ch| queue << ch} end nil end end
true
d9ef40c3ee07d79bcb07fa84e060df503c07434b
Ruby
nictse500/BEWD_NYC_9_Homework
/_Nicolas_Tse/stocks/runner.rb
UTF-8
961
3.8125
4
[]
no_license
require_relative 'lib/Portfolio' def greet puts "Welcome to your virtual portfolio." end def instruction puts "Commands:" puts " Add position: [buy|sell] [shares] [stock symbol]" puts " Current status: status" puts " Quit: quit" end greet instruction portfolio = Portfolio.new() command = [] while command.first != "quit" do command = gets.split(' ').map {|x| x.downcase.chomp} if command.first == "status" portfolio.print_status elsif ["buy", "sell"].include? command.first if command.length != 3 then puts "Please enter number of shares and the stock symbol" instruction else action = command[0] shares = command[1].to_i symbol = command[2].upcase if action == "buy" portfolio.buy_stock(symbol, shares) elsif action == "sell" portfolio.sell_stock(symbol, shares) end end elsif command.first != "quit" puts "Invalid command." #validation instruction end end puts "Summary" portfolio.print_status
true
7d1b7951eebc9a58a7dfc13b975dea0dbca2d702
Ruby
NSHipster/nshipster.com
/_plugins/extended-date-filter.rb
UTF-8
2,302
3.046875
3
[ "MIT", "CC-BY-NC-4.0" ]
permissive
# frozen_string_literal: true require 'time' module Jekyll module ExtendedDateFilter # Reformat a date using Ruby's core Time#strftime( string ) -> string # with additional replacements. # # %a - The abbreviated weekday name (``Sun'') # %A - The full weekday name (``Sunday'') # %b - The abbreviated month name (``Jan'') # %B - The full month name (``January'') # %c - The preferred local date and time representation # %d - Day of the month (01..31) # %H - Hour of the day, 24-hour clock (00..23) # %I - Hour of the day, 12-hour clock (01..12) # %j - Day of the year (001..366) # %m - Month of the year (01..12) # %M - Minute of the hour (00..59) # %o - Ordinal for the day of the month (st, nd, rd, th...) # %p - Meridian indicator (``AM'' or ``PM'') # %s - Number of seconds since 1970-01-01 00:00:00 UTC. # %S - Second of the minute (00..60) # %U - Week number of the current year, # starting with the first Sunday as the first # day of the first week (00..53) # %W - Week number of the current year, # starting with the first Monday as the first # day of the first week (00..53) # %w - Day of the week (Sunday is 0, 0..6) # %x - Preferred representation for the date alone, no time # %X - Preferred representation for the time alone, no date # %y - Year without a century (00..99) # %Y - Year with century # %Z - Time zone name # %% - Literal ``%'' character # # See also: http://www.ruby-doc.org/core/Time.html#method-i-strftime def date(input, format) return input unless date = datetime(input) return input unless (format = format.to_s) && !format.empty? date.strftime(format.gsub(/%o/, ordinal(date.day))) end private def ordinal(number) return 'th' if (11..13).cover?(number.to_i % 100) case number.to_i % 10 when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th' end end def datetime(date) case date when String Time.parse(date) else date end end end end Liquid::Template.register_filter(Jekyll::ExtendedDateFilter)
true
0a7afde3cc75f25ce20c52efc4795568afa0fa30
Ruby
notmarkmiranda/nfl_suicide_league
/app/models/league_creator.rb
UTF-8
269
2.5625
3
[]
no_license
class LeagueCreator attr_reader :league, :user def initialize(league, user) @league = league @user = user end def save if league.save league.user_leagues.create(user_id: user.id, role: 1) return true end return false end end
true
b181c8b9bf547131203ca04f8f2b3b9a8fedd0e2
Ruby
fuadsaud/bis
/lib/bis.rb
UTF-8
3,743
3.4375
3
[ "MIT" ]
permissive
require 'bis/conversion' require 'bis/version' class Bis include Comparable include Enumerable def self.from_enum(enum) from_string(enum.join) end def self.from_string(string) Bis.new(string.size, value: string.to_i(2)) end attr_reader :size alias_method :length, :size # Future versions of Ruby may have Fixnum#bitlength alias_method :bitlength, :size def initialize(size, value: 0) fail ArgumentError, 'size must be >= 0' if size < 0 @size = size.to_i @store = (value & ((1 << size) - 1)).to_i end def set(index) new_with_same_size.(value: @store | 1 << index) end def clear(index) new_with_same_size.(value: @store & (~(1 << index))) end def [](index) with_valid_index index do |index| @store[index] end end # Not sure if it's a good idead to implement this. # def []=(index, value) # with_valid_bit value do |bit| # case bit # when 1 then set index # when 0 then clear index # end # end # end def concat(other) size_and_value_for(other) do |other_size, other_value| new.(size: size + other_size).(value: (to_i << other_size) | other_value) end end def +(other) size_and_value_for(other + to_i) do |result_size, result| new.(size: result_size).(value: result) end end def &(other) new_with_same_size.(value: other & to_i) end def |(other) new_with_same_size.(value: other | to_i) end def ^(other) new_with_same_size.(value: other ^ to_i) end def <<(amount) new_with_same_size.(value: to_i << amount) end def >>(amount) new_with_same_size.(value: to_i >> amount) end def each return enum_for :each unless block_given? size.times.reverse_each do |bit| yield self[bit] end end def each_byte return enum_for :each_byte unless block_given? full_bitset = if size % 8 != 0 concat((1 << (8 - (size % 8))) - 1) else self end (full_bitset.size / 8).times.reverse_each do |offset| yield Bis.new(8, value: (full_bitset >> offset * 8) & ((1 << 8) - 1)) end end def bytes each_byte.to_a end def to_a each.to_a end def to_i @store end def to_s to_a.join end def <=>(other) to_i <=> Bis(other).to_i end def coerce(other) case other when Integer size_and_value_for(other) do |other_size, other_value| [new.(size: other_size).(value: other_value), self] end else fail TypeError, "#{ self.class } cannot be coerced into #{ other.class }" end end def inspect "<<#{ to_s }>> #{ to_i }" end protected attr_writer :store private def size_and_value_for(bitset_or_integer) yield bitlenght_for(bitset_or_integer), bitset_or_integer.to_i end def with_valid_bit(bit) case bit when 0..1 then yield bit else fail ArgumentError, 'bit must be either 0 or 1' end end def with_valid_index(index) case index when 0..@size then yield index else fail ArgumentError, "index #{index} out of boudaries for #{self}" end end def new_with_same_size new.(size: size) end def new(factory = self.class) ->(size: size) { ->(value: 0) { factory.new(size, value: value) } } end def bitlenght_for(bitset_or_integer) case bitset_or_integer when Bis then bitset_or_integer.size when 0..1 then 1 when 2 then 2 when Integer then Math.log2(bitset_or_integer).ceil else fail ArgumentError, 'cannot resolve a bitlength' + "#{ bitset_or_integer }. Must be either Integer" + 'or Bis' end end end
true
75a2a8b48b40941c114355f8ebe0da778b2a5004
Ruby
Fiveolioo/my-collect-onl01-seng-pt-050420
/lib/my_collect.rb
UTF-8
193
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(languages) counter = 0 collection = [] while counter < languages.length collection << yield(languages[counter]) counter += 1 end collection end
true
cf1f09aae80ebe73abb913c5424fa5ba84d3ac16
Ruby
RossAllenBell/adhoc-slcsp
/slcsp.rb
UTF-8
1,213
2.75
3
[]
no_license
require 'csv' require './zipcode_record' require './plan_record' require './slcsp_record' def main zips_filename = ARGV[0] || fail('expecting: [zips filename] [plans filename] [slcsp filename]') plans_filename = ARGV[1] || fail('expecting: [zips filename] [plans filename] [slcsp filename]') slcsp_filename = ARGV[2] || fail('expecting: [zips filename] [plans filename] [slcsp filename]') zip_records = CSV.parse( File.read(zips_filename), headers: :first_row, header_converters: :symbol, skip_blanks: true, ).map(&:to_h).map do |row| ZipcodeRecord.new(**row) end plan_records = CSV.parse( File.read(plans_filename), headers: :first_row, header_converters: :symbol, skip_blanks: true, ).map(&:to_h).map do |row| PlanRecord.new(**row) end slcsp_records = CSV.parse( File.read(slcsp_filename), headers: :first_row, header_converters: :symbol, skip_blanks: true, ).map(&:to_h).map do |row| SlcspRecord.new(**row) end puts 'zipcode,rate' slcsp_records.each do |slcsp_record| slcsp_record.set_rate!( zip_records: zip_records, plan_records: plan_records, ) puts slcsp_record.csv_data end end main
true
928659d2e618c30dfbd548d7d84f92410efaffe6
Ruby
fascox/RubyPoker
/lib/Hand.rb
UTF-8
1,139
3.5
4
[]
no_license
require_relative 'Card' require_relative 'PokerEngine' class Hand attr_accessor :hand, :rank, :rank_score, :rank_desc def initialize @rules_engine = PokerEngine.instance @hand = [] end def build_from_string(string_hand) @hand = [] cards_on_hand = string_hand.split cards_on_hand.each do |o| begin @hand << Card.new(o) rescue #@hand.pop end end end def build_from_set(cards) @hand = cards end def << (card) @hand << card end def validate @hand.size == 5 || @hand.size == 7 end def to_s @hand.join(' ') end def to_suits @hand.map { |x| x.to_suit }.join end def to_faces @hand.map { |x| x.to_face }.join end def to_values @hand.map { |x| x.val } end def rank_score evaluate end def evaluate # guard unless validate @rank_score = -1 @rank_desc = 'invalid hand' return end @rules_engine.rankings.each_key do |rank| info = @rules_engine.send rank, self @rank = info.desc @rank_score = info.score @rank_desc = "#{info.desc} with #{info.card}" break if @rank_score > 0 end @rank_score end end
true
4d43d691f376545ad3d2b3cce5fc15fadad7e80e
Ruby
batteries76/language-tree-react-frontend
/utils/test_path_builder.rb
UTF-8
1,618
3.09375
3
[]
no_license
tree = { name: "a", children: [ { name: "b", children: [] }, { name: "c", children: [ { name: "e", children: [] }, { name: "f", children: [ { name: 'i', children: [] } ] }, { name: "g", children: [] } ] }, { name: "d", children: [ { name: "h", children: [] } ] } ] } final_array = [] level = 0 def path_find(tree, continuing_array, final_array) puts "START" puts "TREE name" print tree[:name] puts puts puts "CONTINUING" print continuing_array puts puts "FINAL" print final_array puts continuing_array << tree[:name] final_array << continuing_array continuing_array_copy = continuing_array.select {|e| true } puts "AFTER THE MIDDLE" puts "TREE name" print tree[:name] puts puts "CONTINUING" print continuing_array puts puts "FINAL" print final_array puts puts "END" puts tree[:children].each do |child| path_find(child, continuing_array_copy, final_array) end end path_find(tree, [], final_array) print(final_array) puts
true
c55997fbefd4b75049376f244faf0bcbd9fdc6ee
Ruby
danrice92/sep-assignments
/02-algorithms/6-improving-complexity/improving_complexity_version_three.rb
UTF-8
1,052
4.09375
4
[]
no_license
# Create a version that improves the space complexity. Put the solution in a file named improving_complexity_version_three.rb. # I attempted to improve the space complexity by using a space-efficient while loop and deleting elements that had already been sorted rather than keeping them in array that would take up more memory. This implementation was detrimental to time performance, but should mean it uses the least space. require 'benchmark' def space_conscious_ruby(*arrays) combined_array = [] arrays.each do |array| array.each do |value| combined_array << value end end while combined_array.length > 0 lowestValue = combined_array[0] combined_array.each do |val| if val < lowestValue lowestValue = val end end puts combined_array.delete(lowestValue) end end firstArray = [87, 2, 5, 9, 13, 1, 93, 33, 19, 81, 46, 88, 3, 6, 7, 91, 37] secondArray = [22, 12, 99, 18, 84, 70, 55, 30, 72, 68, 11, 90, 5, 15, 21] puts Benchmark.measure { space_conscious_ruby(firstArray, secondArray) }
true
cdc456d7d56cb730e1bbc331504c45e219e17ae2
Ruby
johnsonchmatc/mad_libs_2017_fall
/app/models/bus_stop.rb
UTF-8
185
3.015625
3
[]
no_license
class BusStop attr_accessor :stop_id, :route, :lat, :lon def initialize(stop_id, route, lat, lon) @stop_id = stop_id @route = route @lat = lat @lon = lon end end
true
0e2731bdf358ea64b374f41f6dbbc3fc788c1e9d
Ruby
jwpincus/m4-final-starter
/spec/features/mark_as_read_spec.rb
UTF-8
1,513
2.65625
3
[]
no_license
require "rails_helper" RSpec.describe "can mark links as read", :js => :true do before(:each) do user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) @link = Link.create(url:"https://turing.io", title:"Turing") user.links << @link end scenario "Mark a link as read" do visit "/" within('.link .read-status') do expect(page).to have_text("false") end click_on "Mark as Read" within('.link .read-status') do expect(page).to have_text("true") end end scenario "Mark a link as un-read" do @link.update_attributes(read: true) visit "/" within('.link .read-status') do expect(page).to have_text("true") end click_on "Mark as Unread" within('.link .read-status') do expect(page).to have_text("false") end end end # Mark a link as "read" or "unread" # # There is some JS already written to help you mark a link as read. # # Next to each unread link I should see an option to "Mark as Read". # Clicking this should visibly change the read status to true, and the change should persist. # Next to each read link I should see an option to "Mark as Unread". # Clicking this should change the read status to false, and the change should persist. # Read links should be stylistically differentiated from unread links. You could gray them out or use a strike through or anything you think appropriately informs the user that their link is read or unread.
true
75fa205850bbb3538b9fde297e97b785936ad99d
Ruby
YuukiMAEDA/AtCoder
/Ruby/ABC/B/Palace.rb
UTF-8
182
2.75
3
[]
no_license
n=gets.to_i t,a=gets.split.map(&:to_i) h=gets.split.map(&:to_i) min,mini=0 h.each_with_index{|hn,i| tem=(a-t+0.006*hn).abs if i==0||tem<min then min=tem;mini=i+1 end } puts mini
true
b0930404d28a3a4e1894b721ea5955844de41aab
Ruby
noma4i/telegrammer
/lib/telegrammer/data_types/voice.rb
UTF-8
614
2.609375
3
[ "MIT" ]
permissive
module Telegrammer module DataTypes # Telegram Voice data type # # @attr [String] file_id Unique file identifier # @attr [Integer] duration Duration of the audio in seconds as defined by sender # @attr [String] mime_type Optional. Mime type of a file as defined by sender # @attr [String] file_size Optional. File size # # See more at https://core.telegram.org/bots/api#video class Voice < Telegrammer::DataTypes::Base attribute :file_id, String attribute :duration, Integer attribute :mime_type, String attribute :file_size, Integer end end end
true
cc040f018805bd22486e150bc0e0771f39e15e45
Ruby
kchu17/Divvy
/backend/routes/users.rb
UTF-8
999
2.546875
3
[]
no_license
require_relative 'util' require_relative '../classes/user' require_relative '../classes/group' require 'sinatra' require 'sinatra/json' def sanitize_user user user = user.to_h user['sanitized'] = true; # user.delete 'password' # user.delete 'salt' user end get '/users/:id' do user = User::from_id(params['id']) or return USER_DOESNT_EXIST json sanitize_user user end get '/users/:id/find_groups' do groups = Group::list_all or return json ok: false json ok: true, groups: groups end get '/users/username/:username' do user = User::from_username(params['username']) or return USER_DOESNT_EXIST json sanitize_user user end put '/users/:id' do user = User::from_id(params['id']) or return USER_DOESNT_EXIST data = parse_body(request.body.read){ |err| return err } user.update! data or return status 200 json ok: true end delete '/users/:id' do user = User::from_id(params['id']) or return USER_DOESNT_EXIST user.delete! or return status 200 json ok: true end
true
1820ed7d2f502224ee9727fbfde95acc36902e65
Ruby
slbccfl/Ironhack
/Week2/bloginator/spec/blog_spec.rb
UTF-8
1,078
2.90625
3
[]
no_license
# spec/blog_spec.rb require_relative "../lib/blog.rb" require_relative "../lib/post.rb" RSpec.describe "Blog object tests" do describe "create a blog" do it "creates a blog and initializes posts as an empty array" do test_blog = Blog.new expect(test_blog.posts).to eq([]) end it "can add a post to the blog" do test_blog = Blog.new test_post1 = Post.new("Test1",Time.now,"Test text 1","Fantasy","R.L.Stein") test_blog.add_post(test_post1) expect(test_blog.posts).to eq([test_post1]) test_post2 = Post.new("Test2",Time.now,"Test text 2","Real Stuff","H.R. Puffenstuff") test_blog.add_post(test_post2) expect(test_blog.posts).to eq([test_post1, test_post2]) end it "can sort blog posts newest to oldest" do test_blog = Blog.new test_post1 = Post.new("Test1",Time.local(2016,1,14),"Test text 1") test_blog.add_post(test_post1) test_post2 = Post.new("Test2",Time.local(2016,2,20),"Test text 2") test_blog.add_post(test_post2) test_blog.sort_posts expect(test_blog.posts).to eq([test_post2, test_post1]) end end end
true
40c82fbecf8327de02357965dabf2648af40dc21
Ruby
m-mrcr/pantry_03
/test/recipe_test.rb
UTF-8
957
3.171875
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/ingredient' require './lib/recipe' class RecipeTest < MiniTest::Test def setup @bread = Ingredient.new("bread", "slices", 120) @recipe = Recipe.new("Peanut Butter & Jelly") end def test_it_exists assert_instance_of Recipe, @recipe end def test_it_initiates_with_attributes assert_equal "Peanut Butter & Jelly", @recipe.name assert_equal Hash.new, @recipe.ingredients end def test_it_can_add_ingredients @recipe.add_ingredient(@bread, 2) expected = {@bread => {"slices" => 2}} assert_equal expected, @recipe.ingredients end def test_it_can_check_quantity_of_ingredient_needed_for_recipe @recipe.add_ingredient(@bread, 2) assert_equal 2, @recipe.check_quantity_necessary(@bread) end def test_it_can_show_total_number_of_calories @recipe.add_ingredient(@bread, 2) assert_equal 240, @recipe.total_calories end end
true
d541de26b07bb25e69286c29be89ca6eddb568ca
Ruby
robinleoknauth/aa_prep
/lib/02_calculator.rb
UTF-8
276
3.65625
4
[]
no_license
def add(a, b) a + b end def subtract(a, b) a - b end def multiply(a, b) a * b end def divide(a, b) a / b end def power(a, b) a ** b end def factorial(n) return 1 if n == 0 n * factorial(n - 1) end def sum(arr) return 0 if arr.empty? arr.reduce(:+) end
true
d729a04b07dc87da05b52fb5714771a7a3f45a3b
Ruby
sumajirou/ProjectEuler
/p080.rb
UTF-8
246
2.984375
3
[]
no_license
require 'BigDecimal' sum = 0 1.upto(100) do |n| next if n == Math.sqrt(n).floor**2 sqrtn = BigDecimal(n).sqrt(100) sum += sqrtn.to_s[2..101].chars.map(&:to_i).sum end p sum # 40886 # [Done] exited with code=0 in 0.521 seconds
true
69c4d7bbfda618453f742ca844f2568713dad074
Ruby
scottsek/learn_to_program
/PreCourse/AskQuestion.rb
UTF-8
340
3.421875
3
[]
no_license
def ask question while true puts question reply = gets.chomp.downcase if (reply == 'yes' || reply == 'no') if reply == 'yes' true return else false return end break else puts 'Please answer "yes" or "no".' end end # This is what we return (true or false). end puts ask 'Do you like me?'
true
11ffafff295e1e08bedb24b929e9d82f748cb5d4
Ruby
DouglasAllen/Learning_Ruby-book-code
/ch01/matz_24.rb
UTF-8
93
3.078125
3
[]
no_license
#!/usr/bin/env ruby def hello yield end hello { puts "Hello, Matz!" } # => Hello, Matz!
true
2f91faba29c066a402611df4a2194d4e7c651222
Ruby
colorbox/AtCoderLog
/abc/105/d.rb
UTF-8
343
2.84375
3
[]
no_license
n, m = gets.strip.split.map(&:to_i) a = gets.strip.split.map {|e| e.to_i%m } m_a = [a.first] (1...n).each do |i| m_a[i] = (m_a[i-1]+a[i])%m end numbers = m_a.group_by(&:itself) result=0 numbers.each do |_, arr| c = arr.length next if c<2 result += c*(c-1)/2 #p result end result += m_a.count(&:zero?) #p"--" #p a #p m_a p result
true
4f8ab38d9af0728063f53f06347dce7b4d9345e3
Ruby
ga-wolf/WDI12_Homework
/TimothyTsui/week_05/games/app/controllers/magic_eight_ball_controller.rb
UTF-8
459
2.515625
3
[]
no_license
class MagicEightBallController < ApplicationController def question end def answer @question = params[:question] answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Signs point to yes', 'Yes', 'Outlook good', 'Most likely', 'As I see it, yes', 'You may rely on it', 'Yes, definitely', "Don't count on it", 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'] @answer = answers[rand(15)] end end
true
62ffc7875f3f79fba99edaad5cf0a8699b11eff7
Ruby
seokhyungan/lotto_recommend
/app/controllers/home_controller.rb
UTF-8
1,776
2.921875
3
[]
no_license
require "nokogiri" require "open-uri" class HomeController < ApplicationController $lotto=(1..45).to_a.sample(7).sort def index #숫자 랜덤으로 출력 6자리 @lotto = $lotto end def numberCheck #이번주 번호 파싱 url = "http://nlotto.co.kr/gameResult.do?method=byWin" data = Nokogiri::HTML(open(url)) #파싱한 번호 배열에 입력 및 "" 마크 제거 scrapNumbers = data.css('article div div p img').map{|i| i['alt']} scrapNumbers = scrapNumbers.map{|n|eval n} #출력된 번호와 파싱된 번호 비교 match_numbers = $lotto & scrapNumbers match_count = match_numbers.count() #if match_count == 6 # result ="1등" #elsif match_count == 5 && my_numbers.include?(bonus_number) # result = "2등" #elsif match_count == 4 # result = "3등" #elsif match_count == 3 # result = "4등" #elsif match_count == 2 # result = "5등" #else result = "꽝" #end case match_count when 6 result ="1등" when 5 result ="2등" when 4 result ="3등" when 3 result ="4등" when 2 result ="5등" when 1 result ="6등" else result ="꽝" end @paramLotto = $lotto @scrapNumbers = scrapNumbers @match_numbers=match_numbers @result=result end end
true
13910ef86e84f6da7267876cdce31619e530fc1f
Ruby
Franerial/Thinknetica_Ruby_Base-Railway
/lesson_8/main.rb
UTF-8
13,062
3.484375
3
[]
no_license
require_relative "station" require_relative "route" require_relative "train" require_relative "passenger_train" require_relative "cargo_train" require_relative "wagon" require_relative "passenger_wagon" require_relative "cargo_wagon" require_relative "exeption_classes" class Interface private attr_accessor :trains, :routes, :stations, :stop, :wagons public MAIN_MENU = <<~here Пожалуйста, выберите действие 1 : Создать станцию, поезд или маршрут 2 : Произвести операции с созданными объектами 3 : Получить текущие данные об объектах 4 : Выход из программы here CREATION_MENU = <<~here 1 : Создать станцию 2 : Создать поезд 3 : Создать маршрут here TRAIN_MANAGE_MENU = <<~here Выберите операцию 1 : Добавить маршрут поезду 2 : Добавить вагон поезду 3 : Отцепить вагон от поезда 4 : Переместить поезд вперёд 5 : Переместить поезд назад here MANAGE_MENU = "1 : Управление поездами\n2 : Управление маршрутами\n3 : Управление вагонами" ROUTE_MANAGE_MENU = "1 : Добавление станции в маршрут\n2 : Удаление станции из маршрута" def initialize @stop = false @trains = [] @routes = [] @stations = [] @wagons = [] end def start loop do if stop puts "Программа завершена" break end puts MAIN_MENU action = gets.chomp.to_i perform_action(action) end end private def perform_action(action) case action when 1 create_object when 2 perform_object_operation when 3 show_objects_info when 4 self.stop = true end end def create_object puts CREATION_MENU action = gets.chomp.to_i case action when 1 create_station when 2 create_train when 3 create_route end end def perform_object_operation puts MANAGE_MENU action = gets.chomp.to_i case action when 1 trains_manage when 2 routes_manage when 3 wagons_manage end end def trains_manage puts "Список доступных поездов" trains.each_with_index { |train, index| puts "#{index} : #{train.number}" } puts "Выберите индекс поезда, над которым желайте выполнить операцию (начиная с 0)" train_index = gets.chomp.to_i puts TRAIN_MANAGE_MENU action = gets.chomp.to_i case action when 1 add_route_to_train(train_index) when 2 add_wagon_to_train(train_index) when 3 remove_wagon_from_train(train_index) when 4 move_train_to_next_station(train_index) when 5 move_train_to_previous_station(train_index) end end def routes_manage puts "Список всех маршрутов:" routes.each_with_index { |route, index| puts "#{index} : #{route.get_stations_list.map { |station| station.name }}" } puts "Выберите индекс маршрута, над которым желайте произвести действие (начиная с 0)" route_index = gets.chomp.to_i puts ROUTE_MANAGE_MENU action = gets.chomp.to_i case action when 1 add_station_to_route(route_index) when 2 remove_station_from_route(route_index) end end def wagons_manage puts "Список всех доступных вагонов:" wagons.each_with_index { |wagon, index| puts "#{index} : #{wagon}" } puts "Выберите индекс вагона, которому желайте занять место/объём (начиная с 0)" wagon_index = gets.chomp.to_i if wagons[wagon_index].class == PassengerWagon wagons[wagon_index].take_seat puts "Место успешно занято!" elsif wagons[wagon_index].class == CargoWagon puts "Введите занимаемый объём:" capacity = gets.chomp.to_i wagons[wagon_index].add_capacity(capacity) puts "Объём успешно занят!" end end def create_station puts "Пожалуйста, введите имя станции" station_name = gets.chomp stations << station = Station.new(station_name) puts "Станция была успешно добавлена!" end def create_train puts "Пожалуйста, введите номер поезда (в формате XXX-XX, где X - цифра или буква, дефис не обязателен)" train_number = gets.chomp puts "Пожалуйста, введите тип поезда (cargo (грузовой) или passenger (пассажирский))" train_type = gets.chomp.strip.to_sym raise TrainArgumentError, "Введён некорректный тип поезда!" unless [PassengerTrain::TYPE, CargoTrain::TYPE].include? train_type trains << PassengerTrain.new(train_number) if train_type == PassengerTrain::TYPE trains << CargoTrain.new(train_number) if train_type == CargoTrain::TYPE puts "Поезд был успешно добавлен!" rescue TrainArgumentError => e puts e.message puts "Повторите попытку!" retry end def create_route puts "Список доступных станций:" stations.each_with_index { |station, index| p "#{index} : #{station.name}" } puts "Введите индекс начальной станции (начиная с нуля)" index_first = gets.chomp.to_i puts "Введите индекс конечной станции (начиная с нуля)" index_last = gets.chomp.to_i routes << Route.new(stations[index_first], stations[index_last]) puts "Маршрут был успешно создан!" end def show_objects_info show_stations_info show_trains_info show_routes_info show_wagons_info end def show_stations_info puts puts "Подробная информация по станциям:" puts stations.each_with_index do |station, index| puts "Станция номер #{index}" puts "Имя станции: #{station.name}" puts "Информация по поездам на станции:" if station.trains.empty? puts "Поезда на станции отсутствуют" else station.iterate_through_trains { |train, index| puts "Поезд #{index}\nНомер поезда: #{train.number}\nТип поезда: #{train.type}\nКоличество вагонов: #{train.wagons_list.size}\n" } end puts end end def show_trains_info puts "Подробная информация по поездам:" puts trains.each_with_index do |train, index| puts "Поезд номер #{index}" puts "Регистрационный номер поезда: #{train.number}" puts "Тип поезда: #{train.type}" puts "Текущая скорость поезда: #{train.current_speed}" puts "Текущая станция поезда: #{train.current_station.name}" if !train.current_station.nil? puts "Текущий маршрут поезда: #{train.route.get_stations_list.map { |station| station.name }}" if !train.route.nil? puts "Текущий список вагонов поезда: #{train.wagons_list}" if !train.wagons_list.empty? puts end end def show_routes_info puts "Подробная информация по маршрутам:" puts routes.each_with_index do |route, index| puts "Маршрут номер #{index}" puts "Начальная станция маршрута: #{route.first_station.name}" puts "Конечная станция маршрута: #{route.last_station.name}" puts "Все станции маршрута по порядку: #{route.get_stations_list.map { |station| station.name }}" puts end end def show_wagons_info block1 = Proc.new do |wagon, index| puts "Номер вагона: #{index}" puts "Тип вагона: #{wagon.class::TYPE}" if wagon.class == PassengerWagon puts "Общее количество мест в вагоне: #{wagon.total_seats_number}" puts "Количество занятых мест в вагоне: #{wagon.occupied_seats_number}" puts "Количество свободных мест в вагоне: #{wagon.free_seats_number}" puts elsif wagon.class == CargoWagon puts "Общий объём вагона: #{wagon.total_capacity}" puts "Занятый объём: #{wagon.occupied_capacity}" puts "Свободный объём: #{wagon.free_capacity}" puts end end puts "Подробная информация по вагонам у каждого поезда:" puts trains.each do |train| puts "Поезд #{train}" if train.wagons_list.empty? puts "Вагоны у поезда отсутствуют" puts else train.iterate_through_wagons &block1 end end end def add_route_to_train(train_index) puts "Список доступных маршрутов:" routes.each_with_index { |route, index| puts "#{index} : #{route.get_stations_list.map { |station| station.name }}" } puts "Выберите индекс маршрута, который желайте добавить (начиная с 0)" route_index = gets.chomp.to_i trains[train_index].add_route(routes[route_index]) puts "Маршрут успешно добавлен!" trains[train_index].current_station.accept_train trains[train_index] end def add_wagon_to_train(train_index) if trains[train_index].type == :cargo puts "Введите общий объём вагона:" capacity = gets.chomp.to_i wagon = CargoWagon.new(capacity) elsif trains[train_index].type == :passenger puts "Введите общее количество мест в вагоне:" seats = gets.chomp.to_i wagon = PassengerWagon.new(seats) end trains[train_index].add_wagon(wagon) wagons << wagon puts "Вагон успешно добавлен!" end def remove_wagon_from_train(train_index) trains[train_index].remove_wagon puts "Вагон успешно отсоединён!" end def add_station_to_route(route_index) puts "Список всех доступных станций:" stations.each_with_index { |station, index| puts "#{index} : #{station.name}" } puts "Введите индекс станции, который желайте добавить в маршрут" station_index = gets.chomp.to_i routes[route_index].add_intermediative_station(stations[station_index]) puts "Станция успешно добавлена в маршрут!" end def remove_station_from_route(route_index) puts "Список всех доступных станций в маршруте:" routes[route_index].get_stations_list.each_with_index { |station, index| puts "#{index} : #{station.name}" } puts "Введите индекс станции, который желайте удалить из маршрута (начиная с 0)" station_index = gets.chomp.to_i station = routes[route_index].get_stations_list[station_index] routes[route_index].remove_intermediative_station(station) puts "Станция успешно удалена!" end def move_train_to_next_station(train_index) trains[train_index].current_station.send_train trains[train_index] if trains[train_index].move_to_next_station puts "Поезд успешно перемещён на следующую станцию!" else puts "Вы находитесь на последней станции. Дальнейшее перемещение вперёд невозможно!" end trains[train_index].current_station.accept_train trains[train_index] end def move_train_to_previous_station(train_index) trains[train_index].current_station.send_train trains[train_index] if trains[train_index].move_to_previous_station puts "Поезд успешно перемещён на предыдущую станцию!" else puts "Вы находитесь на первой станции. Дальнейшее перемещение назад невозможно!" end trains[train_index].current_station.accept_train trains[train_index] end end interface = Interface.new interface.start
true
bb46f8d45731b67add59826ff7be7e3e7a685357
Ruby
adoan91/essential-ruby
/loop_each02.rb
UTF-8
180
3.796875
4
[]
no_license
list = [] count = 1 while count <= 5 print "Enter a name: " name = gets.chomp count += 1 list << name end new_list = list.sort new_list.each do |name| puts "Hi " + name end
true
05b12703d3a36584331c09e7ed307d0a4b94a272
Ruby
kkelleey/exercism
/ruby/bowling/bowling.rb
UTF-8
2,538
3.390625
3
[]
no_license
require 'pry' class Game def initialize @current_frame = Frame.new(0) @finished_frames = [] end def roll(pins) raise 'Pins must have a value from 0 to 10' unless pins.between?(0, 10) raise 'Should not be able to roll after game is over' if game_over? add_roll(pins) end def score raise 'Score cannot be taken until the end of the game' unless game_over? @finished_frames.reduce(0) { |a, e| a + e.score(@finished_frames) } end private def game_over? @finished_frames.length == 10 end def add_roll(pins) @current_frame.add_roll(pins) if @current_frame.finished? @finished_frames << @current_frame @current_frame = Frame.new(@current_frame.index + 1) end end end class Frame attr_reader :rolls, :index def initialize(index) @index = index @rolls = [] end def add_roll(pins) check_pin_count(pins) @rolls << pins end def finished? return false if @rolls.empty? if tenth_frame? tenth_frame_finished? else @rolls.length == 2 || strike? end end def score(all_frames) return strike_score(all_frames) if strike? return spare_score(all_frames) if spare? open_score end def strike? first_throw == 10 end def first_throw @rolls.first end def tenth_frame? @index == 9 end private def check_pin_count(pins) raise 'Pin count exceeds pins on the lane' if pins > remaining_pins end def remaining_pins return 10 if @rolls == [10, 10] || spare? return 10 - @rolls[1] if @rolls[1] && strike? 10 - @rolls.first.to_i end def strike_score(all_frames) return @rolls.reduce(:+) if tenth_frame? 10 + next_two_throws(all_frames) end def next_two_throws(all_frames) next_frame = all_frames[@index + 1] first_throw = next_frame.first_throw second_throw = if next_frame.strike? && !next_frame.tenth_frame? all_frames[@index + 2].first_throw else next_frame.rolls[1] end first_throw + second_throw end def open_score @rolls.reduce(:+) end def spare? @rolls.first(2).reduce(:+) == 10 end def spare_score(all_frames) return @rolls.reduce(:+) if tenth_frame? next_frame = all_frames[@index + 1] next_throw = next_frame.first_throw 10 + next_throw end def tenth_frame_finished? return @rolls.length == 3 if strike? || spare? @rolls.length == 2 end end class BookKeeping VERSION = 1 end
true
196770bb5cf53ef05c9a7f925e9c8b84102b4174
Ruby
pranavtrivedi1993/api_server
/app/models/user.rb
UTF-8
446
2.71875
3
[]
no_license
class User < ApplicationRecord has_secure_password # Validations validates :first_name, length: { minimum: 2 }, allow_nil: true, allow_blank: true validates :last_name, length: { minimum: 2 }, allow_nil: true, allow_blank: true validates :email, presence: true, uniqueness: { case_sensitive: false } # Instance method to get full name of user def full_name [first_name, last_name].compact.reject(&:empty?).join(" ") end end
true
94eb58d47b3b4e34c6c2da84fda08a74d5959190
Ruby
RickWayne/heartbeat
/Email.rb
UTF-8
2,423
2.65625
3
[]
no_license
#!/usr/bin/env ruby # Email.rb # Handle email parts of heartbeat require 'net/pop' require 'net/smtp' require 'rubygems' require 'bundler/setup' require 'mailfactory' class EmailHeaderChecker attr_reader :found attr_writer :verbose def initialize(server,account='fewayne',pw='Schn0krd',verbosity=false) @found = false @verbose = verbosity print("starting...\n") if @verbose Net::POP3.start( server,110,account,pw ) do |pop| if pop.mails.empty? then puts 'no mail.' else print("#{pop.mails.size} messages\n") if @verbose hdrNum=0 @hdrs = pop.mails.collect { |m| if @verbose && hdrNum % 300 == 0 print(".") end hdrNum += 1 m.header } print("got headers\n") if @verbose end end end # search email headers for a matching line. if we wanted to get really # fancy, we could also search the content def find(scanREStr) @found = false print("starting...\n") if @verbose scanRE = Regexp.new(scanREStr) @hdrs.each do |hdr| if @verbose print(" --- new header --- \n") print(hdr) print(" ------------------ \n") end if hdr.index(scanRE) @found = true break; end end @found end def EmailHeaderChecker.test tm = Time.now print("Start time: #{tm}\n") ehc = EmailHeaderChecker.new('facstaff.wisc.edu','fewayne', 'Schn0krd', true) print("find returns: #{ehc.find("Subject:\s*ET for #{(tm.year).to_s} #{(tm.yday-1).to_s} at 43.5 -89.25")}\n") tm = Time.now print("Stop time: #{tm}\n") end end def sendAlert(alertStr) mail = MailFactory.new() mail.to = "fewayne@wisc.edu" mail.from = "asig@www.soils.wisc.edu" mail.subject = "Status check (heartbeat)" mail.body = alertStr Net::SMTP.start('localhost',25) do |smtp| # smtp.send_message mail.to_s, 'asig@www.soils.wisc.edu','6083341928@txt.att.net' smtp.send_message mail.to_s, 'asig@www.soils.wisc.edu','fewayne@wisc.edu' end # `echo 'Content-type: text/html\n#{alertStr}' | mail -s 'skipped a heartbeat!' fewayne@wisc.edu` # `echo 'Content-type: text/html\n#{alertStr}' | mail -s 'ASIG Heartbeat Checker' wlbland@wisc.edu` end
true
f4359e87dbde19213035f8f3d0734561fb30b63e
Ruby
srobert1953/introduction-to-programming
/variables/variable_scope.rb
UTF-8
849
4.09375
4
[]
no_license
# Variable can be placed in multiple places in the program and this can be refered as a scope of variable # !!! If the variable is placed inside a block of code, it is not accesible outside of the block !!! # But if the variable is created outside of some block, it is accessible inside of any block. a = 3 3.times do |n| a = 5 b = 0 end puts a # Displays 5, so the block changed it from 3 to 5 # puts b # Gets error: `<main>': undefined local variable or method `b' for main:Object (NameError) # Another example: (comment line 13 in order to work) x = 10 def method x = 4 y = 3 end puts x # puts y # Error here d = [2, 3, 4] for i in d do v = 22 end puts "#{v} inside for" # This works, because v is actually not part of a block, this is a bit confusing and well explained. # It may be clear later...
true
c35972cf4f82a9ccd48977a792bee3508327a563
Ruby
cpoirier/schemaform
/lib/schemaform/language/schema_definition.rb
UTF-8
2,704
2.546875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby # ============================================================================================= # Schemaform # A DSL giving the power of spreadsheets in a relational setting. # # [Website] http://schemaform.org # [Copyright] Copyright 2004-2012 Chris Poirier # [License] Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================================= module Schemaform module Language class SchemaDefinition include QualityAssurance def self.process( schema, &block ) schema.use do dsl = new(schema) schema.enter do dsl.instance_eval(&block) schema.verify() end end end def initialize(schema, &block) @schema = schema end # # Defines an entity within the Schema. def define_entity( name, parent = nil, &block ) if parent && !parent.is_an?(Model::Entity) then parent = @schema.entities.find(parent, checks_enabled?) end EntityDefinition.process(@schema, name, parent, &block) end # # Defines a tuple within the Schema. def define_tuple( name, &block ) TupleDefinition.build(name, &block) end # # Defines a simple (non-entity) type. def define_type( name, base_name = nil, modifiers = {} ) fail_todo "not refactored yet" @schema.instance_eval do check do type_check( :name, name, [Symbol, Class] ) type_check( :modifiers, modifiers, Hash ) end if base_name && !@types.member?(base_name) then fail_todo "deferred types" else modifiers[:base_type] = @types[base_name] @types.register modifiers[:name], UserDefinedType.new(modifiers) end end end # # Adds attributes to an existing tuple type. def augment_tuple( name, &block ) tuple_type = @schema.find_tuple_type(name) tuple_type.define( &block ) end end # SchemaDefinition end # Language end # Schemaform
true
338ef1829e79e951549bc5f103d19f6bd9f9de8c
Ruby
semyonovsergey/int-brosayZavod
/lesson 8/eachDemo.rb
WINDOWS-1252
151
3.25
3
[]
no_license
# encoding: cp866 while true print ": " a = gets print ": " b = gets (a...b).each do |x| puts x end puts "=====" end
true
869e45fc96dc9ff49d61efcf257e73998b2417c3
Ruby
lucasDechenier/study-ruby-rails
/modulo_02/06_hashs.rb
UTF-8
176
3.65625
4
[]
no_license
# Hash é uma lista do tipo chave => valor # Determinanos qual vai ser a chave, diferente de um array que é fixo h = {"a" => "Lucas", "r" => "rails"} puts h["a"] puts h["r"]
true
ef382f9367b2a2b98ed0d264e18f37a3018c9c5b
Ruby
oahtpham/keys-of-hash-prework
/lib/keys_of_hash.rb
UTF-8
242
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Hash def keys_of(*arguments) array = arguments new_array = [] array.each do |arg| self.each do |key, value| if arg == value new_array.push(key) end end end new_array end end
true
50efaca3f2f2092634184609c002c9450e6efc04
Ruby
todddrinkwater/ruby_hangman
/brute_force/hangman.rb
UTF-8
3,069
3.921875
4
[]
no_license
def admin_input print "ADMIN: Please enter your choosen word:" hangman_word = gets.chomp letters_remaining = hangman_word.length return hangman_word end def check_input_type(word) #also check string length is greater than 0 regex_comparison = /[\d\s_\W]+/ type_check = word.scan(regex_comparison) if type_check.length < 1 then word.downcase! else print "Word must only contain letters with no spacing. Please try again." admin_input end end def user_guess puts "Guess a letter!" guessed_letter = gets.chomp regex_comparison = /[\d\s_\W]/ type_check = guessed_letter.scan(regex_comparison) puts type_check if (guessed_letter.length > 1) || (guessed_letter.length <= 0) puts "Please enter only a single letter." user_guess elsif type_check.length > 0 puts "Please use only letters." user_guess else $guesses_array.push(guessed_letter) return guessed_letter end end def includes_letter?(word, guessed_letter) word_array = word.split('') if word_array.include?(guessed_letter) puts "Bullseye!" elsif word_array.include?(guessed_letter) == false puts "Sorry, you guessed wrong." $lives_remaining -= 1 puts ". ." puts " ^" end end def display_guess_word(admin_word) word_display = [] word_array = admin_word.chars # check that param is safe to use. admin_word_length = admin_word.length admin_word_length.times { word_display.push("_") } word_display = word_array.map { |letter| $guesses_array.include?(letter) ? letter : "_"} # word_array.each_index do |admin_index| # $guesses_array.each_index do |guesses_index| # if $guesses_array[guesses_index] == word_array[admin_index] # word_display[admin_index] = word_array[admin_index] # end # end # word_display # end $letters_remaining = word_display.count("_") print "GUESS WORD: #{word_display.join(" ")}\n" end def check_game_status if ($letters_remaining > 0) && ($lives_remaining > 0) puts "Lives remaining: #{$lives_remaining}" puts "Letters remaining: #{$letters_remaining}" puts "- - - - - - - - - - - - - - - " game_time_logic end if $letters_remaining < 1 puts "Lifesaver. You win!" puts "Play again? Enter YES or NO" play_again = gets.chomp if play_again == "YES" run_hangman else return "BYE!" end end if $lives_remaining < 1 puts "YOU LOSE." puts "Play again? Y or N?" play_again = gets.chomp if play_again == "yes" then run_hangman else puts "BYE!" end end end def game_time_logic guessed_letter = user_guess includes_letter?($hangman_guess_word, guessed_letter) print "Letters guessed: #{$guesses_array}\n" display_guess_word($hangman_guess_word) check_game_status end def run_hangman $guesses_array = [] #global vars not secure $lives_remaining = 7 puts "Welcome to HANGMAN, mannnnn." $hangman_guess_word = admin_input $letters_remaining = $hangman_guess_word.length check_input_type($hangman_guess_word) game_time_logic end run_hangman
true
1d4f35a62a428d6c47ba47667c60be22d7b18ccc
Ruby
loganmeetsworld/advent-of-code
/2015/ruby/advent20.rb
UTF-8
705
3.71875
4
[]
no_license
max_presents = 29000000 div_presents = max_presents / 11 decimal_presents = max_presents / 10 max_houses = 50 house_hash = Hash.new(0) lowest_number = nil house_hash_2 = Hash.new(0) lowest_number_2 = nil 1.upto(decimal_presents) do |e| 1.upto(decimal_presents / e) do |n| house_hash[n * e] += e * 10 end end house_hash.find do |key, value| if value >= max_presents lowest_number = key end end puts "Part 1: " + lowest_number.to_s 1.upto(div_presents) do |e| 1.upto([50, (div_presents / e)].min) do |n| house_hash_2[n * e] += e * 11 end end house_hash_2.find do |key, value| if value >= max_presents lowest_number_2 = key end end puts "Part 2: " + lowest_number_2.to_s
true
df226e4fab290b4d3ba768f2a67619ae64d84fdb
Ruby
RobinWagner/PrepCourse-Book1
/Chapter8_Files/exercise1.rb
UTF-8
435
3.359375
3
[]
no_license
# Exercise 1 my_file = File.new("simple_file.txt", "w+") my_file.close File.open("simple_file.txt", "w") { |file| file.write("adding first line of text") } sample = File.open("simple_file.txt", "w+") sample.puts("another example of writing to a file.") sample.close simple = File.read("simple_file.txt") original = File.new("original_file.txt", "w+") File.open(original, "a") do |file| file.puts simple end File.read(original)
true
813f2adc95a2fae58c488fb61c3613c84f06246e
Ruby
smileyuichi/gyakuten_Ruby_answer
/q9.rb
UTF-8
377
3.546875
4
[]
no_license
# 次の配列を用いて,期待通りの出力結果になるようにコードを書いて下さい。 names = ["田中", "佐藤", "佐々木", "高橋"] names.each.with_index(1) do |name,i| puts "会員No.#{i} #{name}さん" end # 期待結果 # ``` # 会員No.1 田中さん # 会員No.2 佐藤さん # 会員No.3 佐々木さん # 会員No.4 高橋さん # ```
true
373999d728f84185942ec759dc3b757b93301692
Ruby
johnvoon/launch_school
/exercise_sets_for_101_109/advanced1.rb/select_fibonacci.rb
UTF-8
530
3.828125
4
[ "MIT" ]
permissive
def return_fibonaccis(array) fibonacci_array = [1, 1] first, last = [1, 1] fibonacci = 0 loop do fibonacci = first + last break if fibonacci >= array.length - 1 fibonacci_array << fibonacci first = last last = fibonacci end fibonacci_array end def select_fibonacci(array) array.select do |number| fibonacci_numbers = return_fibonaccis(array) fibonacci_numbers.include?(array.index(number)) end end array = [1,2,3,4,5,6,7,8,9,10] p return_fibonaccis(array) p select_fibonacci(array)
true
573a01fed36e83e4a24838954765991935d473d6
Ruby
learn-academy-2021-bravo/week-4-assessment-Vivean28
/code_challenges.rb
UTF-8
3,385
4.4375
4
[]
no_license
# ASSESSMENT 4: Ruby Coding Practical Questions # MINASWAN ✌️ # --------------------1) Create a method that takes in an array of words and a letter and returns all the words that contain that particular letter. # I need to create a method called my_letters # that takes in an array of words # Later, my method needs to return all the words that contain that particular letter. # I need to use the .inculdes? to look for the for 't', and 'o' beverages_array = ['coffee', 'tea', 'juice', 'water', 'soda water'] letters_array = ['a', 'b', 'c', 'd', 'l', 'm', 'n', 'o'] letter_o = 'o' # Expected output: ['coffee', 'soda water'] letter_t = 't' # Expected output: ['tea', 'water', 'soda water'] # def my_letters array # array.map do |value| # value.split('') # end # end # p my_letters beverages_array def my_letters array,letter array.map do |value| value.split('') if value.include?(letter) p value end end end my_letters beverages_array, letter_t # def my_letters(array, letter) # # get the values out of the array # # each is looking # array.each_with_index do |value, index| # one_word = value.split() # one_word.each do |value| # if value == letter # p array[index] # end # end # end # end # my_letters(beverages_array, letter_o) # -------------------2) Create a method that takes in a string and removes all the vowels from the string. Use the test variables provided. HINT: Check out this resource: https://ruby-doc.org/core-2.6/String.html#method-i-delete # Create a method that takes in a parameter (string) # I first need to say string.split('') that way every letter in my index is splited # I need to assign my splited string that say I can use it to itirate through it # And removes all the vowels from the string # To remove all vowls, (aeiou) album1 = 'Rubber Soul' # Expected output: 'Rbbr Sl' album2 = 'Sgt Pepper' # Expected output: 'Sgt Pppr' album3 = 'Abbey Road' # Expected output: 'bby Rd' # def remove_vowels string # my_splited_arra = string.split('') # end # p remove_vowels album1 def remove_vowels string #my_splited_arra = string.split('') string.delete "aeiouAEIOU" end p remove_vowels album1 p remove_vowels album2 p remove_vowels album3 # def remove_vowels string # string.map do |value| # end # end # array.map do |value| # value.split('') # if value.include?(letter) # p value # end # end # --------------------3a) Create a class called Bike that is initialized with a model, wheels, and current_speed. The default number of wheels is 2. The current_speed should start at 0. Create a get_info method that returns a sentence with all the data from the bike object. # Expected output example: 'The Trek bike has 2 wheels and is going 0 mph.' class Bike def initialize @model = "model" @wheels = 2 @current_speed = 0 end def get_info "The Trek bike has 2 wheels and is going 0 mph." end end p new_one = Bike.new # -------------------3b) Add the ability to pedal faster and brake. The pedal_faster method should increase the speed. The brake method should decrease the speed. The bike cannot go negative speeds. # Expected output example: my_bike.pedal_faster 10 => 10 # Expected output example: my_bike.brake 15 => 0
true
be21cf51ccdcf77b91ecae87eee74d736feb8a3d
Ruby
kevinrood/simple_record
/lib/simple_record/attributes.rb
UTF-8
8,544
2.640625
3
[]
no_license
module SimpleRecord module Attributes # For all things related to defining attributes. def self.included(base) #puts 'Callbacks included in ' + base.inspect =begin instance_eval <<-endofeval def self.defined_attributes #puts 'class defined_attributes' @attributes ||= {} @attributes endendofeval endofeval =end end def defined_attributes @attributes ||= {} @attributes end def has_attributes(*args) has_attributes2(args) end def has_attributes2(args, options_for_all={}) # puts 'args=' + args.inspect # puts 'options_for_all = ' + options_for_all.inspect args.each do |arg| arg_options = {} if arg.is_a?(Hash) # then attribute may have extra options arg_options = arg arg = arg_options[:name].to_sym end type = options_for_all[:type] || :string attr = Attribute.new(type, arg_options) defined_attributes[arg] = attr if defined_attributes[arg].nil? # define reader method arg_s = arg.to_s # to get rid of all the to_s calls send(:define_method, arg) do ret = get_attribute(arg) return ret end # define writer method send(:define_method, arg_s+"=") do |value| set(arg, value) end define_dirty_methods(arg_s) end end def define_dirty_methods(arg_s) # Now for dirty methods: http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html # define changed? method send(:define_method, arg_s + "_changed?") do @dirty.has_key?(sdb_att_name(arg_s)) end # define change method send(:define_method, arg_s + "_change") do old_val = @dirty[sdb_att_name(arg_s)] [old_val, get_attribute(arg_s)] end # define was method send(:define_method, arg_s + "_was") do old_val = @dirty[sdb_att_name(arg_s)] old_val end end def has_strings(*args) has_attributes(*args) end def has_ints(*args) has_attributes(*args) are_ints(*args) end def has_floats(*args) has_attributes(*args) are_floats(*args) end def has_dates(*args) has_attributes(*args) are_dates(*args) end def has_booleans(*args) has_attributes(*args) are_booleans(*args) end def are_ints(*args) # puts 'calling are_ints: ' + args.inspect args.each do |arg| defined_attributes[arg].type = :int end end def are_floats(*args) # puts 'calling are_ints: ' + args.inspect args.each do |arg| defined_attributes[arg].type = :float end end def are_dates(*args) args.each do |arg| defined_attributes[arg].type = :date end end def are_booleans(*args) args.each do |arg| defined_attributes[arg].type = :boolean end end def has_clobs(*args) has_attributes2(args, :type=>:clob) end @@virtuals=[] def has_virtuals(*args) @@virtuals = args args.each do |arg| #we just create the accessor functions here, the actual instance variable is created during initialize attr_accessor(arg) end end # One belongs_to association per call. Call multiple times if there are more than one. # # This method will also create an {association)_id method that will return the ID of the foreign object # without actually materializing it. # # options: # :class_name=>"User" - to change the default class to use def belongs_to(association_id, options = {}) arg = association_id arg_s = arg.to_s arg_id = arg.to_s + '_id' attribute = Attribute.new(:belongs_to, options) defined_attributes[arg] = attribute # todo: should also handle foreign_key http://74.125.95.132/search?q=cache:KqLkxuXiBBQJ:wiki.rubyonrails.org/rails/show/belongs_to+rails+belongs_to&hl=en&ct=clnk&cd=1&gl=us # puts "arg_id=#{arg}_id" # puts "is defined? " + eval("(defined? #{arg}_id)").to_s # puts 'atts=' + @attributes.inspect # Define reader method send(:define_method, arg) do return get_attribute(arg) end # Define writer method send(:define_method, arg.to_s + "=") do |value| set(arg, value) end # Define ID reader method for reading the associated objects id without getting the entire object send(:define_method, arg_id) do get_attribute_sdb(arg_s) end # Define writer method for setting the _id directly without the associated object send(:define_method, arg_id + "=") do |value| # rb_att_name = arg_s # n2 = name.to_s[0, name.length-3] set(arg_id, value) # if value.nil? # self[arg_id] = nil unless self[arg_id].nil? # if it went from something to nil, then we have to remember and remove attribute on save # else # self[arg_id] = value # end end send(:define_method, "create_"+arg.to_s) do |*params| newsubrecord=eval(arg.to_s.classify).new(*params) newsubrecord.save arg_id = arg.to_s + '_id' self[arg_id]=newsubrecord.id end define_dirty_methods(arg_s) end def has_many(*args) args.each do |arg| #okay, this creates an instance method with the pluralized name of the symbol passed to belongs_to send(:define_method, arg) do #when called, the method creates a new, very temporary instance of the Activerecordtosdb_subrecord class #It is passed the three initializers it needs: #note the first parameter is just a string by time new gets it, like "user" #the second and third parameters are still a variable when new gets it, like user_id return eval(%{Activerecordtosdb_subrecord_array.new('#{arg}', self.class.name ,id)}) end end #Disclaimer: this whole funciton just seems crazy to me, and a bit inefficient. But it was the clearest way I could think to do it code wise. #It's bad programming form (imo) to have a class method require something that isn't passed to it through it's variables. #I couldn't pass the id when calling find, since the original find doesn't work that way, so I was left with this. end def has_one(*args) end def self.handle_virtuals(attrs) @@virtuals.each do |virtual| #we first copy the information for the virtual to an instance variable of the same name eval("@#{virtual}=attrs['#{virtual}']") #and then remove the parameter before it is passed to initialize, so that it is NOT sent to SimpleDB eval("attrs.delete('#{virtual}')") end end # Holds information about an attribute class Attribute attr_accessor :type, :options def initialize(type, options=nil) @type = type @options = options end def init_value(value) return value if value.nil? ret = value case self.type when :int ret = value.to_i end ret end end end end
true
632f19d97d8bc2e8156ab529b267c45aa16f107a
Ruby
MihaiLiviuCojocar/ruby-practice
/sort_string.rb
UTF-8
185
3.5
4
[]
no_license
def sort_string(string) # arr = [] # for i in (0..string.length-1) # arr << string.slice(i) # end p string.chars.sort.join # print arr.sort.join end sort_string('gergerge')
true
a781da421021030e49e3e70261f3f59109045804
Ruby
NNWaller/parrot-ruby-cb-000
/parrot.rb
UTF-8
88
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def parrot (someString = "Squawk!") puts "#{someString}" return "#{someString}" end
true
92038d49614efbb5e4936e5eb579e5e7bcad7762
Ruby
beachio/hammer-gem
/lib/hammer/parsers/modules/optimizer.rb
UTF-8
824
3.3125
3
[ "MIT" ]
permissive
# Optimizer module mixin. This goes directly into Parser as all parsers can be optimized. # This causes an optimize(text) method to be called before parse(). If the parse() method has branches in it for optimizing anyway, you may not need an optimize() method. # Usage: # class Thing # def optimize(text) # return text # end # include Optimizer # end module Hammer module Optimizer attr_accessor :optimized def optimized?; optimized; end def self.included(base) _parse = base.instance_method(:parse) base.send :define_method, :parse do |text| parse = _parse.bind(self) text = parse.call(text) if self.respond_to?(:optimize) && self.optimized? return optimize(text) else return text end end end end end
true
6b25d205f86018cb38bf99e825054aaa2355eefc
Ruby
leftees/battleship
/lib/ship.rb
UTF-8
1,637
3.109375
3
[]
no_license
class Ship attr_reader :location, :type, :xsize def initialize(matrix, options) @xsize = options[:size] @type = options[:type] @matrix = matrix @location = [] end def build begin destroy ship_len = @xsize mask = [] # random start point begin xy = [rand(@matrix.size), rand(@matrix.size)] mask = take_mask(xy) end while mask.empty? save(xy) ship_len -= 1 while(!ship_len.zero? && !mask.size.zero?) do # random next direction xy = mask.delete_at(rand(mask.size)) neighberhood = take_mask(xy, @location.last) if !neighberhood.empty? save(xy) mask = neighberhood ship_len -= 1 end end end while !ship_len.zero? self end private def destroy @location.each { |xy| @matrix[xy[0]][xy[1]] = ' ' } @location = [] end def save(xy) @location.push(xy) @matrix[xy[0]][xy[1]] = true end # returns valid surrounding mask def take_mask(xy, exception = nil) return [] unless xy x, y = xy[0], xy[1] return [] if @matrix[x][y] === true mask = Array.new mask[0] = [x-1, y ] if (x-1) >= 0 mask[1] = [x, y-1] if (y-1) >= 0 mask[2] = [x, y+1] if (y+1) < @matrix.size mask[3] = [x+1, y ] if (x+1) < @matrix.size clean(mask, exception) end def clean(mask, exception) mask = mask.select{ |item| not item.nil? || item === exception } mask.each do |item| if @matrix[item[0]][item[1]] === true return [] end end mask end end
true
eb36fac29bcd56b140691a1e39bba903728f743a
Ruby
SirRiixz/exercises
/examples/alphabet.rb
UTF-8
171
3.546875
4
[]
no_license
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","t","u","v","w","x","y"] alphabet.push("z") for letters in alphabet puts "This letter is #{letters}" end
true
d4c53801ecc491481555fddaf2d40212995090f3
Ruby
Lakshadeep/MusicSearch
/controllers/Track.rb
UTF-8
311
2.59375
3
[]
no_license
require 'rest-client' require 'uri' class Track attr_accessor :name,:album,:artist,:wiki,:id,:img_link,:duration def initialize(name,album,artist,wiki,img_link,duration,id) @name = name @album = album @artist = artist @wiki = wiki @img_link = img_link @id = id @duration = duration end end
true
f997bd4ca539440fa2506a592b1efdbfe49799a6
Ruby
arpodol/ruby_small_problems
/easy7/capitalize_words.rb
UTF-8
1,077
4
4
[]
no_license
def word_cap(string) string_array = string.split(' ') string_array.map! {|word| word.capitalize} string_array.join(' ') end p word_cap('four score and seven') == 'Four Score And Seven' p word_cap('the javaScript language') == 'The Javascript Language' p word_cap('this is a "quoted" word') == 'This Is A "quoted" Word' def word_cap_adv_one(string) string_array = string.split(' ') string_array.map! do | word | word.downcase! letters = word.split('') letters[0].upcase! letters.join('') end string_array.join(' ') end p word_cap_adv_one('the javaScript language') == 'The Javascript Language' p word_cap_adv_one('four score and seven') == 'Four Score And Seven' def word_cap_adv_two(string) string_array = string.split('') string_array.map.with_index do | letter, index | string_array[index-1] == ' ' || index == 0 ? letter.upcase! : letter.downcase! end string_array.join('') end p word_cap_adv_two('the javaScript language') == 'The Javascript Language' p word_cap_adv_two('four score and seven') == 'Four Score And Seven'
true
f9d11206d2f121b924fc07b7351ce11f76eb7804
Ruby
bulletproofMUG/learn_ruby
/05_book_titles/book.rb
UTF-8
415
3.5
4
[]
no_license
class Book attr_reader :title def title=(input) argv = input.split.map.with_index do |x, i| if x =~ /[0-9]/ x elsif i == 0 x.capitalize! elsif x == "i" x.capitalize! elsif %w(the a an and in of).include?(x) x else x.capitalize! end end @title = argv.join(" ") end end
true
c2855e9366e4ad1337572705459fba7f16f9dbd5
Ruby
ZuhairS/Algorithms-and-Data-Structures
/Assortment/Search_element_in_sorted_rotated_arr.rb
UTF-8
1,142
3.515625
4
[]
no_license
def search_rotated_sorted_arr(arr, target) return nil if arr.empty? mid_idx = arr.length / 2 if arr[mid_idx] == target return mid_idx elsif arr.first < arr[mid_idx] if target < arr[mid_idx] && target >= arr.first search_rotated_sorted_arr(arr[0...mid_idx], target) else rec = search_rotated_sorted_arr(arr[mid_idx + 1..-1], target) rec + mid_idx + 1 if rec end else if target <= arr.last && target > arr[mid_idx] rec = search_rotated_sorted_arr(arr[mid_idx + 1..-1], target) rec + mid_idx + 1 if rec else search_rotated_sorted_arr(arr[0...mid_idx], target) end end end def search_pivot_rotated_sorted_arr(arr) return nil if arr.empty? mid_idx = arr.length / 2 if arr.first < arr[mid_idx] && arr[mid_idx] < arr.last return 0 elsif arr.first > arr[mid_idx] search_pivot_rotated_sorted_arr(arr[0...mid_idx]) elsif arr.first < arr[mid_idx] search_pivot_rotated_sorted_arr(arr[mid_idx + 1..-1]) + mid_idx + 1 end end p search_rotated_sorted_arr([5, 6, 7, 8, 9, 1, 2, 3, 4], 4) p search_pivot_rotated_sorted_arr([5, 6, 7, 8, 9, 1, 2, 3, 4])
true
1af8a2a4c72dc70136a191d8f192cf551e034965
Ruby
GreyCat/chie
/spec/recordset_spec.rb
UTF-8
1,841
2.671875
3
[ "MIT" ]
permissive
require 'spec_helper' require 'mysql2' describe RecordSet do describe '#total_pages' do it 'should return single page if not pagination requested' do rs = RecordSet.new(nil, {}) expect(rs.total_pages).to eq(1) end it 'should return 1 page if we have less than one page of records' do rs = RecordSet.new(nil, total_count: 3, per_page: 10, page: 1) expect(rs.total_pages).to eq(1) end it 'should return 1 page if we have exactly one page of records' do rs = RecordSet.new(nil, total_count: 10, per_page: 10, page: 1) expect(rs.total_pages).to eq(1) end it 'should return 2 pages if we have more than one page, but less than full two pages of records' do rs = RecordSet.new(nil, total_count: 11, per_page: 10, page: 1) expect(rs.total_pages).to eq(2) rs = RecordSet.new(nil, total_count: 13, per_page: 10, page: 1) expect(rs.total_pages).to eq(2) end it 'should return 2 pages if we have exactly 2 pages of records' do rs = RecordSet.new(nil, total_count: 20, per_page: 10, page: 1) expect(rs.total_pages).to eq(2) end end describe '#to_a' do it 'returns all rows as array, each row wrapped in Record' do result = [ {'a' => 1, 'b' => 2}, {'a' => 3, 'b' => 4}, ] rs = RecordSet.new(result) rs_to_a = rs.to_a expect(rs_to_a.count).to eq(2) expect(rs_to_a[0]).to eq(Record.new({'a' => 1, 'b' => 2})) expect(rs_to_a[1]).to eq(Record.new({'a' => 3, 'b' => 4})) end end describe '#map' do it 'maps rows using given block' do result = [ {'a' => 1, '_header' => 2}, {'a' => 3, '_header' => 4}, ] rs = RecordSet.new(result) rs_map = rs.map { |x| x.header } expect(rs_map).to eq([2, 4]) end end end
true
c329f02f0f2ba853f2524c91e6e2220b5df7a18a
Ruby
ipresilia/store
/store.rb
UTF-8
1,915
3.78125
4
[]
no_license
# Helper Methods def print_divider puts "*" * 40 puts "\n" end # Shopping Cart @shopping_cart = [] # List of Products @products = [ { reference_number: 123, name: "MacBook Air", price: 1200 }, { reference_number: 124, name: "MacBook Pro", price: 2000 }, { reference_number: 125, name: "Apple Watch", price: 700 }, { reference_number: 126, name: "iMac", price: 2500 }, { reference_number: 127, name: "iPod", price: 300 }, { reference_number: 128, name: "iPad", price: 500 } ] # Welcome user & Show products def welcome_n_product_show print_divider puts "What will you buying from us today?\n This is what we have available:\n Each product has its own reference number\n which you can use to select the products with." print_divider @products.each do |product| puts "#{product[:reference_number]} - #{product[:name]} €#{product[:price]}" end end #User Selection def select_product puts "Select the item(s) you want to buy by using their number of reference: " gets.chomp.to_i end # Add Selection to cart def add_to_cart(reference_number) product = look_for_product(reference_number) if product != nil && product[:reference_number] == reference_number @shopping_cart << product puts "Congrats. The following has been added to the cart successfully: '#{product[:name]}' costing €#{product[:price]}" else puts "Invalid selection. Please try again with an existing reference_number." print_divider end end # Check and see whether input matches reference_number def look_for_product(reference_number) @products.each do |product| if product[:reference_number] == reference_number.to_i return product end end end # Visit store (Used to print methods) loop do print_divider puts "Welcome to Apple Fan Boy!\n\n" welcome_n_product_show product_reference_number = select_product add_to_cart(product_reference_number) end
true