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
a168086d6368fd0b76f02e3f6f1bf705ab9cea40
Ruby
ivncastillo/desafio_ruby_ciclos
/gen.rb
UTF-8
190
3.65625
4
[]
no_license
def gen(x) abcedario='abcdefghijklmnopqrstuvwxyz' if x<= 27 && x>0 return abcedario[0,x] else puts 'introduzca un numero entero postivo menor a 27' end end
true
eb4019fba10eb51fb0215018e8af87a850238c9e
Ruby
jugyo/logy
/lib/logy/command.rb
UTF-8
519
2.546875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- module Chlgr class Command @@commands = {} class << self def add(name, &block) @@commands[name.to_sym] = block end def get(name) @@commands[name.to_sym] end def search(text) return [] if text.nil? || text.empty? @@commands.keys.map{|i|i.to_s}.grep(/^#{Regexp.quote(text)}/).map{|i|i.to_sym} end def find_all @@commands end def clear @@commands.clear end end end end
true
1f4719a46e8dd14ec1b3f1b042991cf7838f337b
Ruby
ThilakshanArulnesan/ar-exercises
/exercises/exercise_1.rb
UTF-8
500
3.25
3
[]
no_license
require_relative '../setup' require_relative '../lib/store' puts "Exercise 1" puts "----------" # Your code goes below here ... s1 = Store.create(name: "Burnaby", annual_revenue: 300_000, mens_apparel: true, womens_apparel: true) s2 = Store.create( name: "Richmond", annual_revenue: 1_260_000, mens_apparel:false, womens_apparel:true ) s3 = Store.create( name: "Gastown", annual_revenue: 190_000, mens_apparel:true, womens_apparel:false ) puts "There are #{Store.count} stores."
true
a6a314f9d87493eaeabf5d13d3064de2d1ca3ec8
Ruby
uejonuba/reverse-each-word-cb-000
/reverse_each_word.rb
UTF-8
128
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(word) array = word.split() result = array.collect {|part| part.reverse} return result.join(" ") end
true
7eb84e717dbcb2243cda4bf655c8876d8a62e4cf
Ruby
bonniepan02/fizz_buzz
/lib/looper.rb
UTF-8
661
2.921875
3
[]
no_license
require 'rule_factory_mapper' require 'fizz_buzz' require 'rule_config_parser' require 'rule_repository' # Loop through to concatenate fizzbuzz run rule results class Looper DELIMETER = ' '.freeze def initialize mapper = RuleFactoryMapper.new parser = RuleConfigParser.new(mapper) config_path = File.expand_path('../rule_files/test.json', __dir__) rule_repository = RuleRepository.new(config_path: config_path, config_parser: parser) @fizz_buzz = FizzBuzz.new(rule_repository) end def run(num) result = (1..num).map { |i| @fizz_buzz.run_rule(i) } result.join(DELIMETER) end end
true
ad2131311c8b03b894db7a7516b86b994f2e5888
Ruby
samgd/dlx
/lib/dlx/node.rb
UTF-8
1,397
3.265625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Dlx class Node attr_reader :row, :col, :header attr_accessor :up, :right, :down, :left def initialize(row, col, header, up = self, right = self, down = self, left = self) @row, @col = row, col @header = header @up, @right, @down, @left = up, right, down, left end def link(nodes) nodes.each_pair { |dir, node| send("#{dir}=", node) } end def remove(type) header.total -= 1 if type == :column simple_remove(type) end def restore(type) header.total += 1 if type == :column simple_restore(type) end # Traverses doubly linked list in the specified direction. # Begins with yieding adjacent node, breaks _before_ yielding self. def each_in(direction) return enum_for(:each_in, direction) unless block_given? node = self until (node = node.send(direction)) == self do yield node end end def to_s "Node[#{row}][#{col}]" end private def simple_remove(type) case type when :row left.right = right right.left = left when :column up.down = down down.up = up end end def simple_restore(type) case type when :row left.right = self right.left = self when :column up.down = self down.up = self end end end end
true
bfad66899b87a15d079071f0d484fcdd60a38669
Ruby
austinandrade/mastermind
/test/game_test.rb
UTF-8
1,000
2.65625
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/mastermind' require './lib/printer' # require './lib/player_guess_matcher' require 'pry' class GameTest < Minitest::Test def test_post_win skip game = Game.new sandwich = mastermind.post_win("p") assert_equal true, sandwich end def test_it_has_attributes game = Game.new assert_equal 0, game.guess_count assert_equal false, game.game_over assert_nil game.start_time assert_nil game.end_time # binding.pry end def test_winning_code_length game = Game.new assert_equal 4, game.create_winning_code.length end def test_set_start_time skip game = Game.new assert_equal Time.now, game.set_start_time end def test_set_end_time skip game = Game.new assert_equal rex, game.set_end_time end def test_time_elapsed game = Game.new game.start_time game.end_time assert_equal (@end_time - @start_time), game.time_elapsed end end
true
8c23ec3b432da35833564d1140796caa8f6f91b4
Ruby
harryFBloch/ruby-music-library-cli-online-web-ft-092418
/lib/artist.rb
UTF-8
518
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_accessor :name, :songs extend EasyModule::ClassMethods extend Concerns::Findable include EasyModule::InstanceMethods @@all = [] def initialize(name) super end def self.all @@all end def genres return_array = self.songs.map {|song| song.genre}.uniq end def add_song(song) song.artist = self unless song.artist self.songs << song unless self.songs.include?(song) self.genres << song.genre if song.genre.class == Genre end end
true
1c10e8a04da0a6a6a1deb7202268655e3295a701
Ruby
paulief/interview-practice
/mth_to_last.rb
UTF-8
1,264
4.03125
4
[]
no_license
# https://www.hackerrank.com/contests/programming-interview-questions/challenges/m-th-to-last-element class Node attr_accessor :val, :forward, :backward def initialize(val) @val = val end end class LinkedList attr_accessor :head, :tail def initialize(head) @head = head @tail = head end def add(node) @head.backward = node node.forward = @head @head = node end end def get_last_node(list) curr = list.head while !curr.forward.nil? curr = curr.forward end curr end def list_from_vals(vals) list = LinkedList.new(Node.new(vals[0])) rest = vals[1..vals.length-1] unless rest.empty? rest.each { |val| list.add(Node.new(val)) } end # make it circular list.head.backward = list.tail list.tail.forward = list.head list end def get_mth_to_last(list, m) curr = list.head (1..m).each do curr = curr.backward end curr.val end # code execution starts here inp = $stdin.read.split("\n") m = Integer(inp[0]) vals = inp[1].split(' ') if m > vals.length puts 'NIL' else list = list_from_vals(vals) puts get_mth_to_last(list, m) end
true
431c28f632d0823232d5ae8f3f8c866a1cbb9cb5
Ruby
invisibill/invisibill-ruby-client
/lib/invisibill-ruby-client/api_client.rb
UTF-8
1,610
2.734375
3
[ "MIT" ]
permissive
require 'typhoeus' API_SCHEME = ENV['API_SCHEME'] || 'https' API_HOST = ENV['API_HOST'] || 'api.invisi-bill.com' API_USER_AGENT = ENV['API_USER_AGENT'] || 'invisibill-ruby-client api' API_MAX_ATTEMPTS = (ENV['API_MAX_ATTEMPTS'] || 5).to_i module Invisibill class ApiClient class << self def base_url "#{API_SCHEME}://#{API_HOST}" end end def initialize(token) @token = token end def get(uri, params = { }) send_request(:get, uri, params) end def post(uri, params = { }) send_request(:post, uri, params) end def put(uri, params = { }) send_request(:put, uri, params) end def delete(uri, params = { }) send_request(:delete, uri, params) end def send_request(method, uri, params) attempts = 0 begin params = [:post, :put, :patch].include?(method.to_s.downcase.to_sym) ? { body: JSON.dump(params) } : { params: params } headers = api_request_headers headers['Content-Type'] = 'application/json' if [:post, :put, :patch].include?(method.to_s.downcase.to_sym) params.merge!(headers: headers) Typhoeus.send(method.to_s.downcase.to_sym, "#{ApiClient.base_url}/api/#{uri}", params) rescue Exception => ex attempts = attempts + 1 retry if attempts < API_MAX_ATTEMPTS end end private def api_authorization_header "bearer #{@token}" end def api_request_headers { 'User-Agent' => API_USER_AGENT, 'Authorization' => api_authorization_header } end end end
true
f7fb77c2cd55ccd8a958ff74dc111bb54dbb7abc
Ruby
northerner/adventofcode2017
/day5.rb
UTF-8
529
3.328125
3
[]
no_license
def step_count(instructions_string) instructions = instructions_string.split.map(&:to_i) location = 0 steps = 0 in_bounds = true while in_bounds steps = steps + 1 next_location = instructions[location] + location in_bounds = (0..instructions.size-1).include?(next_location) if in_bounds change_by = instructions[location] >= 3 ? -1 : 1 instructions[location] = instructions[location] + change_by location = next_location end end steps end puts step_count("0 3 0 1 -3")
true
91da610d80d5cfc0613bb24d9b95afe1f91313a2
Ruby
ChristieRenaud/Course-120
/twenty_one_final.rb
UTF-8
5,490
3.796875
4
[]
no_license
module Hand def hit deck.deal(self) end def stay puts "#{name} stayed. #{name}'s hand is #{hand}" end def busted? total > 21 end def total total = 0 hand.each do |card| total += card.value end hand.select { |card| card.face.first == "Ace" }.count.times do break if total <= 21 total -= 10 end total end def show_hand hand.map do |card| "=> " + card.to_s end end def show_last_card hand.last.to_s end def show_first_card hand.first.to_s end def clear_hand self.hand = [] end end class Player include Hand attr_accessor :name, :hand def initialize @name = '' @hand = [] end def show_flop puts "#{name}'s cards are:" puts show_hand puts "" end end class Dealer include Hand attr_accessor :hand, :name def initialize @hand = [] @name = ["Sonny", "Number 5", "R2D2", "Wall-E", "Hal"].sample end def show_flop puts "#{name}'s cards are:" puts "=> #{show_first_card}" puts "=> ??" puts "" end end class Deck SUITS = ['Hearts', 'Spades', 'Clubs', 'Diamonds'] VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] CARDS = VALUES.product(SUITS) attr_accessor :deck def initialize @deck = [] reset end def deal(player) card = deck.sample player << card deck.delete(card) end def reset (0..51).each do |idx| deck[idx] = Card.new(CARDS[idx]) end end end class Card attr_accessor :face def initialize(face) @face = face end def to_s "The #{face.first} of #{face.last}" end def value if ["King", "Queen", "Jack"].include?(face.first) 10 elsif face.first == "Ace" 11 else face.first.to_i end end end class Game TARGET_NUMBER = 21 attr_accessor :deck, :human, :dealer def initialize @human = Player.new @dealer = Dealer.new @deck = Deck.new end def start display_welcome_message loop do deal_cards show_initial_cards player_turn dealer_turn if !busted? show_ending_hands show_result break unless play_again? reset end goodbye_message end private def display_welcome_message clear puts "Welcome to Twenty-One. The player to" puts "come closest to #{TARGET_NUMBER} without going over wins." assign_name puts "Hello #{human.name}." introduce_dealer puts "Let's play #{TARGET_NUMBER}!" puts "" sleep 1 end def clear system('clear') || system('cls') end def assign_name answer = '' puts "What is your name?" loop do answer = gets.chomp break if answer.match(/\S+/) puts "Invalid response. Please enter a name:" end human.name = answer end def introduce_dealer puts "The dealer today is #{dealer.name}." end def deal_cards 2.times { deck.deal(human.hand) } 2.times { deck.deal(dealer.hand) } end def show_initial_cards human.show_flop sleep 2 dealer.show_flop sleep 2 end def hit(player_hand) deck.deal(player_hand) end def player_turn loop do answer = hit_or_stay if answer.start_with?('s') puts "#{human.name} stayed." puts "" break elsif answer.start_with?('h') hit(human.hand) display_card(human) sleep 2 break if busted? else puts "Invalid response." end end end def hit_or_stay puts "Would you like to hit or stay?" puts "Your card total is #{human.total}" gets.chomp.downcase end def display_card(player) puts "#{player.name} drew:" puts "=> #{player.show_last_card}" puts "" end def answer_starts_with?(letter) answer.downcase.start_with?(letter) end def busted? human.busted? || dealer.busted? end def busted_message if human.busted? puts "#{human.name} busted! #{dealer.name} wins" elsif dealer.busted? puts "#{dealer.name} busted! #{human.name} wins" end end def dealer_turn loop do break unless dealer.total < TARGET_NUMBER - 4 hit(dealer.hand) display_card(dealer) sleep 2 end end def display_totals puts "#{human.name}'s total is #{human.total}." puts "#{dealer.name}'s total is #{dealer.total}." end def display_dealer_won display_totals puts "*** #{dealer.name} won ***" end def display_human_won display_totals puts "*** #{human.name} won ***" end def show_ending_hands puts "#{human.name}'s final cards are:" puts human.show_hand puts "" puts "#{dealer.name}'s final cards are:" puts dealer.show_hand puts "" sleep 2 end def show_result if busted? busted_message elsif dealer.total > human.total display_dealer_won elsif human.total > dealer.total display_human_won else display_totals puts "It's a tie!" end end def play_again? answer = '' loop do puts "Would you like to play again? (y or n)" answer = gets.chomp.downcase break if ['y', 'n'].include?(answer) puts "Invalid response." end answer == "y" end def goodbye_message puts "Thank you for playing Twenty-one. Goodbye" end def reset deck.reset human.clear_hand dealer.clear_hand clear end end Game.new.start
true
9ca4370d9f34dd9e63ad425673b8ab16dbaf42cb
Ruby
macosgrove/toy-robot
/spec/table_spec.rb
UTF-8
1,435
3.109375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_relative "../lib/table" require_relative "../lib/robot" describe Table do subject(:table) { Table.new(3, 6) } describe "#valid_location" do context "When the coordinates are inside the table boundaries" do [[0, 0], [0, 5], [2, 0], [2, 5]].each do |coords| it "returns true" do expect(table.valid_location?(*coords)).to be true end end end context "When the coordinates are outside the table boundaries" do [[-1, 0], [2, -1], [2, 6], [3, 5]].each do |coords| it "returns false" do expect(table.valid_location?(*coords)).to be false end end end end describe "#map" do context "When there are no robots on the table" do it "outputs a blank map" do expect(table.map).to eq <<~MAP +---+ | | | | | | | | | | | | +---+ MAP end end context "When there is a robot on the table" do let(:robot) { instance_double(Robot, x: 2, y: 3, to_c: "^") } before { table.add_robot(robot) } it "outputs a map showing the robot's location and direction" do expect(table.map).to eq <<~MAP +---+ | | | | | ^| | | | | | | +---+ MAP end end end end
true
8501f78864922ef58eaf089c24aa14e17f813fc8
Ruby
ishige-shogo/Atcoder
/atcoder192_contest.rb
UTF-8
1,693
3.203125
3
[]
no_license
#提出の基本となる部分 # 整数の入力 a = gets.to_i # スペース区切りの整数の入力 b,c=gets.chomp.split(" ").map(&:to_i); # 文字列の入力 s = gets.chomp # 出力 print("#{a+b+c} #{s}\n") # a1,a2,a3...anの入力 a = gets.chomp.split(" ").map(&:to_i) # 列の入力 arr=h.times.map{gets.chomp.split("")} puts a.reject{|i| i == X}.join(" ") #入力したものを加工 X,Y,R=gets.chomp.split(" ").map{|i| (i.to_f * 10000).round} b = data.to_s(2) Integer("0377" #----------------------------------------------------------- #ミスったーーーー! X = gets.to_i M = gets.to_i s = X.to_s.split(//).max.to_i + 1 r = X.to_s.split(//).reverse.to_i ans = 0 count=0 while true do break if s>16 ans = X.to_s(s).to_i s += 1 break if ans > M count += 1 end puts count #---------------------------------------------------------------- N,K = gets.chomp.split(" ").map(&:to_i); def kaprekar(m) s = m.to_s s_big = s.split(//).sort.reverse.join.to_i s_small = s.split(//).sort.join.to_i return s_big - s_small end count = 1 while count<=K do N = kaprekar(N) count += 1 end puts N #-------------------------------------------------- S = gets.chomp.split(//) def up(n) [*"A".."Z"].include?(n) end def down(w) [*"a".."z"].include?(w) end count = 0 S.each_with_index do |s,i| if ((i+1).odd? && down(s)) || ((i+1).even? && up(s)) count +=1 end end if count==S.length puts "Yes" else puts "No" end #----------------------------------------------- X = gets.to_i y = X/100 puts (y+1)*100-X
true
edbd938e4f9f6c17a4c867103cdf68c0effac20d
Ruby
SwtCharlie/Quick-Testing
/number randomizer.rb
UTF-8
180
3.25
3
[]
no_license
require "pp" numbers = [1, 2, 3, 4, 5].sort_by { rand } results = [] half = (numbers.size/2.0).ceil half.times do |i| results << [numbers[i], numbers[i+half]] end pp results
true
f6991efa96527dabddaebf8fbf2f1a3ef756818f
Ruby
tanaken0515/try-red-chainer
/examples/seq2seq/data/prepare_dictionaries.rb
UTF-8
676
2.703125
3
[]
no_license
require 'csv' require 'natto' require_relative '../utility/eng' jpn_words = '' eng_words = ' ' nm = Natto::MeCab.new('-Owakati') CSV.foreach('examples/seq2seq/data/jpn_eng_sentences.csv', col_sep: "\t", liberal_parsing: true) do |row| jpn_sentence, eng_sentence = row jpn_words << nm.parse(jpn_sentence) + ' ' eng_words << eng_sentence + ' ' end jpn_dictionary = jpn_words.split(' ').uniq.join("\n") eng_dictionary = (Examples::Seq2seq::Utility::Eng.parse(eng_words).split(' ').uniq - ['"']) .join("\n") File.write('examples/seq2seq/data/jpn_dictionary.csv', jpn_dictionary) File.write('examples/seq2seq/data/eng_dictionary.csv', eng_dictionary)
true
2910b82150d4a8a082f8ec0643b2c1aaa9262bbe
Ruby
Putterhead/ruby-kickstart
/session2/challenge/6_array.rb
UTF-8
2,110
4.90625
5
[ "MIT" ]
permissive
# Write a method named prime_chars? which takes array of strings # and returns true if the sum of the characters is prime. # # Remember that a number is prime if the only integers that can divide it with no remainder are 1 and itself. # # Examples of length three # prime_chars? ['abc'] # => true # prime_chars? ['a', 'bc'] # => true # prime_chars? ['ab', 'c'] # => true # prime_chars? ['a', 'b', 'c'] # => true # # Examples of length four # prime_chars? ['abcd'] # => false # prime_chars? ['ab', 'cd'] # => false # prime_chars? ['a', 'bcd'] # => false # prime_chars? ['a', 'b', 'cd'] # => false # prime number is a number divisible by one and itself, it # must also be a whole number greater than 1. # Something like this; I don't expect this to run but # this is where my thinking is coming from. I still need # to figure out how to get the number of elements # def prime_chars?(string) # string.length % string.length == 1 && string.length % 1 == 0 ? true : false # end # Solution: Ok, so I didnt think of creating an Integer class # but seeing this used helps me understand the use of # classes. First, the method 'prime?' is created, telling # Ruby that if 'self' (string) is < 2 its false. I had to look # up what .upto was and its a public instance method that iterates # the given block, passing in integer values from int (2) up to # and including limit (self) and for those numbers, it returns false # if that number is divisibile by itself without a remainder, otherwise # it returns true. class Integer def prime? return false if self < 2 2.upto Math.sqrt(self) do |i| # according to Rubydocs sqrt returns return false if self % i == 0 # the non-negative square root of x. end # not sure if I understand this fully true end end # Here, its taking the variable 'strings', joining the strings together # evaluating then the length, then the method prime? (above) is being # called, which results in true or false. def prime_chars?(strings) strings.join.length.prime? end
true
e3c740f9b6bad66e6d58cf920abb4cf784554e89
Ruby
raigons/parser
/spec/unit/parser/parser_spec.rb
UTF-8
3,074
2.96875
3
[]
no_license
require 'spec_helper' describe "Parser" do let :raw_message do "09/12/2014, 21:37 - Ramon Henrique: Hello world" end let :raw_message_2 do "09/12/2014, 22:08 - Ramon Henrique: hello again!" end let :raw_message_3 do "09/12/2014, 22:08 - Matheus Gonçalves: Hi!" end subject { WhatsAppParser::Parser.new } context "single messages" do it "should parse a single message into objects" do parsed = subject.parse_message(raw_message)[:message] expect(parsed).to be_a_kind_of WhatsAppParser::Message expect(parsed.content).to eq "Hello world" expect(parsed.hour).to eq "21:37" expect(parsed.date).to eq "09/12/2014" expect(parsed.author).to be_a_kind_of WhatsAppParser::Author expect(parsed.author.name).to eq "Ramon Henrique" end it "should parse messages with special chars" do message = "09/12/2014, 22:08 - Ramon Henrique: Hi, I wanna talk to you in 25/12/2014: test ;)" parsed = subject.parse_message(message)[:message] expect(parsed.date).to eq "09/12/2014" expect(parsed.hour).to eq "22:08" expect(parsed.content).to eq "Hi, I wanna talk to you in 25/12/2014: test ;)" expect(parsed.author.name).to eq "Ramon Henrique" end it "should parse correctly even if the message content includes dates and hours" do message = "09/12/2014, 22:08 - Ramon Henrique: Hi, now is 10/12,2014, 22:15 - am I correct?" parsed = subject.parse_message(message)[:message] expect(parsed.date).to eq "09/12/2014" expect(parsed.hour).to eq "22:08" expect(parsed.content).to eq "Hi, now is 10/12,2014, 22:15 - am I correct?" end it "should parse correctly if the message content includes dates, hours and owner name" do message = "01/12/2014, 23:58 - Ramon Henrique: Hi Matheus Gonçalves: now is 10/12,2014, 13:35 - am I correct?" parsed = subject.parse_message(message)[:message] expect(parsed.date).to eq "01/12/2014" expect(parsed.hour).to eq "23:58" expect(parsed.content).to eq "Hi Matheus Gonçalves: now is 10/12,2014, 13:35 - am I correct?" expect(parsed.author.name).to eq "Ramon Henrique" end it "should extract the message author as a standalone property" do parsed = subject.parse_message(raw_message)[:author] expect(parsed).to be_a_kind_of WhatsAppParser::Author expect(parsed.name).to eq "Ramon Henrique" end end context "multiples messages" do it "should parse a list of messages and return a list of objects" do parsed = subject.parse_messages([raw_message, raw_message_2]) expect(parsed.count).to eq 2 expect(parsed.first[:message].content).to eq "Hello world" expect(parsed.last[:message].content).to eq "hello again!" end it "should parse a list of messages from different authors" do parsed = subject.parse_messages [raw_message, raw_message_3, raw_message_2] expect(parsed.count).to eq 3 expect(parsed.first[:message].content).to eq "Hello world" expect(parsed[1][:message].content).to eq "Hi!" expect(parsed.last[:message].content).to eq "hello again!" end end end
true
159c1f40ce5bd41afc1ef67f5a5e54109ed98a4c
Ruby
peteyluu/coderbyte
/Easy/ab_check.rb
UTF-8
865
4.21875
4
[]
no_license
=begin Have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in "true" because there is exactly three characters between a and b). Otherwise return the string false. =end def ab_check(str) str = str.split('') i = 0 while i < str.length if str[i] == 'a' && str[i+4] == 'b' return true elsif str[i] == 'b' && str[i+4] == 'a' return true end i += 1 end false end puts ab_check("after badly") # => "false" puts ab_check("Laura sobs") # => "true" puts ab_check("away obe") # => "true" puts ab_check("noah obe") # => "true" puts ab_check("far ebs") # => "true" puts ab_check("123adzvb") # => "true" puts ab_check("abccccazzzb") # => "true" puts ab_check("bzzza") # => "true"
true
713d0791dacc417d9aec4307fa92f018a75ece98
Ruby
Jcornick21/factorial
/lib/factorial.rb
UTF-8
348
3.890625
4
[]
no_license
# Computes factorial of the input number and returns it def factorial(number) if number == nil raise ArgumentError.new("number cannot be nil") elsif number == 0 || number == 1 return 1 end count = 0 fac = 1 while count < number fac *= (number - count) count += 1 end return fac # raise NotImplementedError end
true
301dcfc68182ad6ed96252e9ad2857cedfad3783
Ruby
masakisanto/ecuacovid
/lib/ecuacovid/data.rb
UTF-8
4,530
3.109375
3
[ "WTFPL" ]
permissive
require 'date' module Ecuacovid class Data FECHA = ->(valor) { valor.created_at.strftime("%d/%m/%Y") } UNO = ->(valor) { 1 } class << self def calculador(multiplicador, &formula) lambda do |acc, data| result = (acc * multiplicador) return result if data.nil? result + formula.call(data) end end end CONTEO = calculador(0) {|data| data.reduce(0) { |sum, valor| sum + valor } } ACUMULACION = calculador(1) { |data| data.reduce(0) { |sum, valor| sum + valor } } MEDIA_MOVIL = ->(acc, data) { result = PromedioMovil.new(acc) result << data.shift result } def agrupar(datum, options = {}) fn = to_lambda(options[:por]) || FECHA {}.tap do |groups| datum.each do |data| fetch(groups, fn.(data), []) {|c| c << data} end end end def dividir(grupos, divisor) return {predeterminado: grupos} if not divisor {}.tap do |divisiones| grupos.each_pair do |grupo, dataset| agrupar(dataset, por: divisor).each_pair do |division, subset| key = division fetch(divisiones, key, {}) {|c| c[grupo] = subset} end end end end def ordenar(las_divisiones, los_grupos, divisiones) las_divisiones.map do |division| grupos = divisiones[division] los_grupos.map {|nombre_grupo| grupos[nombre_grupo] || []} end end def evaluar(datasets, options = {}) valores_para = to_lambda(options[:evaluar_por]) || UNO datasets.map do |subsets| subsets.map do |data| data.nil? ? [] : (data.map &valores_para) end end end def reducir(datasets, options = {}) valores_para = to_lambda(options[:reducir_por]) || CONTEO datasets.map do |subsets| acc = 0 subsets.map do |data| acc = valores_para.(acc, data) end end end def fechas(groups, options = {}) keys = groups.keys.sort {|a,b| DateTime.parse(a) <=> DateTime.parse(b)} fn = options.fetch(:label) { PorDia } date = fn.(DateTime.parse(keys.first)) end_date = DateTime.parse(keys.last) [].tap do |labels| while date <= end_date labels << date.to_s date >> 1 end end end def maxima(reducidas, options = {}) reducidas.map {|set| set.max}.max end def minima(reducidas, options = {}) reducidas.map {|set| set.min}.min end def porcentajes(max, valores) valores.map do |subset| subset.map {|total| total * 100.0 / max} end end private def to_lambda expression return ->(value) { value[expression] } if to_lambda?(expression) expression end def to_lambda? expression expression.kind_of?(Symbol) end def fetch hash, key, default collection = hash.fetch(key, default) yield(collection) hash.store(key, collection) end class FechaPorDia def initialize(d) @d = d end def to_s @d.strftime("%d/%m/%Y") end def >>(other) @d = @d.next_day(other) end def <=(other) @d <= other end end class FechaPorMes def initialize(d) @d = d end def to_s @d.strftime("%b-%Y") end def >>(other) @d = @d >> other end def <=(other) @d <= other end end class FechaPorSemana def initialize(d) @d = d end def to_s @d.strftime("%V") end def >>(other) @d = @d >> other end def <=(other) @d <= other end end class PromedioMovil attr_reader :dias, :total def initialize(movil) if movil == 0 @acc, @dias = nil, [] else @dias = movil.dias.dup end end def <<(dia) dias.shift if lleno? @dias << dia end def +(movil) total.nil? ? nil : total + movil end def total lleno? ? @dias.map(&:total).sum / n.to_f : nil end private def lleno? @dias.size == n end def n 7 end end PorDia = ->(fecha) { FechaPorDia.new(fecha) } PorMes = ->(fecha) { FechaPorMes.new(fecha) } PorSemana = ->(fecha) { FechaPorSemana.new(fecha) } end end
true
75559dabc16f6fff8ac6ec954f0030358f653e44
Ruby
tylerbrazier/archive
/id3ntify-ruby/tag.rb
UTF-8
6,915
2.828125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'taglib' $args = Arg_Handler.new ARGV # Called by set and edit methods. This does not check if img_path is good # TODO mime type? def set_pic(tag, img_path) return unless tag.class == TagLib::ID3v2::Tag # first remove existing (is this necessary?) tag.remove_frames('APIC') pic = TagLib::ID3v2::AttachedPictureFrame.new pic.description = "Cover" pic.type = TagLib::ID3v2::AttachedPictureFrame::FrontCover pic.picture = File.open(img_path, 'rb') {|f| f.read} tag.add_frame(pic) end def clear(tag) $args.tags_to_clear.each do |type| if type == :cover tag.remove_frames('APIC') if tag.class == TagLib::ID3v2::Tag else # dynamic method call :) tag.send("#{type}=", nil) end end end def set(tag) $args.tags_to_set.each do |type,value| if type == :cover # check if file is readable raise "Unable to read #{value}" unless File.file?(value) set_pic (tag, value) else # dynamic method call :) tag.send("#{type}=", value) end end end def edit(tags) types = $args.tags_to_edit edits = {} if types.include? :all || types.include? :title print "Title: " edits[:title] = gets.chomp end if types.include? :all || types.include? :artist print "Artist: " edits[:artist] = gets.chomp end if types.include? :all || types.include? :album print "Album: " edits[:album] = gets.chomp end if types.include? :all || types.include? :track loop do print "Track: " edits[:track] = gets.chomp.to_i break if edits[:track] != 0 end end if types.include? :all || types.include? :genre print "Genre: " edits[:genre] = gets.chomp end if types.include? :all || types.include? :year loop do print "Year: " edits[:year] = gets.chomp.to_i break if edits[:year] != 0 end end if types.include? :all || types.include? :comment print "Comment: " edits[:comment] = gets.chomp end if types.include? :all || types.include? :cover loop do print "Cover (path): " edits[:cover] = gets.chomp break if File.file? (edits[:cover]) end end tags.each do |tag| edits.each_pair do |k,v| if k == :cover set_pic (tag, v) else # dynamic method call :) tag.send("#{k}=", v) end end end end # Does not check if tag is correct type def purge(tag) ### TODO how should i do this? #keep = ['TIT2','TOPE','TALB','TRCK','....'] # or # keep = {} # keep[:title] = tag.title # keep[:artist] = tag.artist # keep[:album] = tag.album # keep[:track] = tag.track # keep[:genre] = tag.genre # keep[:year] = tag.year # keep[:comment] = tag.comment # and assign them again after removing everything? tag.frame_list.each do |frame| # do stuff here end end def process(filename) puts filename # NOTE it's important that we don't raise from here bc file needs to close TagLib::MPEG::File.open(filename) do |mp3file| begin tags = [] if $args.versions_to_strip.include? (1) good = mp3file.strip(tags=TagLib::MPEG::File::ID3v1) raise "Unable to strip ID3v1 tags from #{filename}" unless good else tags << mp3file.id3v1_tag(create=true) end if $args.versions_to_strip.include? (2) good = !mp3file.strip(tags=TagLib::MPEG::File::ID3v2) raise "Unable to strip ID3v2 tags from #{filename}" unless good else tags << mp3file.id3v2_tag(create=true) end # clear tags.each {|tag| clear(tag)} # set tags.each {|tag| set(tag)} # edit edit(tags) # purge tags.each {|tag| purge(tag) if tag.class == TagLib::ID3v2::Tag} rescue Exception => e mp3file.save # TODO do this here? puts e.message end end end def old_process(filename) tag = mp3file.id3v2_tag create=true # create id3v2 tag if doesn't exist data = {} data[:title] = tag.title data[:artist] = tag.artist data[:album] = tag.album data[:track] = tag.track data[:genre] = tag.genre data[:year] = tag.year data[:comment] = tag.comment data[:cover] = tag.frame_list('APIC').join(',') if $options[:list] puts "Title: #{data[:title]}" puts "Artist: #{data[:artist]}" puts "Album: #{data[:album]}" puts "Track: #{data[:track]}" puts "Genre: #{data[:genre]}" puts "Year: #{data[:year]}" puts "Comment: #{data[:comment]}" puts "Cover: #{data[:cover]}" end if $options[:strip] || $clear.include?("all") unless mp3file.strip then puts "Unable to strip #{filename}!" end else $clear.each do |tag_to_clear| case tag_to_clear when "title" tag.title = nil when "artist" tag.artist = nil when "album" tag.album = nil when "track" tag.track = nil when "genre" tag.genre = nil when "year" tag.year = nil when "comment" tag.comment = nil when "cover" tag.remove_frames('APIC') end end end frames = tag.frame_list frames.each do |frame| puts "#{frame.frame_id} #{frame.to_s}" end #puts tag.frame_list('TIT2').first.to_s #puts tag.frame_list.size # framelist = tag.frame_list # framelist.each {|frame| tag.remove_frame frame} # cover = tag.frame_list('APIC') # puts "APICs #{cover.size}" # strip returns true on success #if $options[:strip] then mp3file.strip end unless mp3file.save(tags=TagLib::MPEG::File::ID3v2, strip_others=true) puts "Unable to save #{filename}!" end end end if $args.switchs[:help] puts $args.help_message # TODO maybe more info if verbose? exit 0 end # process for each argument $args.files.each do |path| if File.directory? (path) Dir.glob("#{path}/**/*.mp3") {|filename| process(filename)} else process(path) end end
true
edfa5ff69b959c4b0e2b5251cfdb170073a95b42
Ruby
notarandomusername/learn_ruby
/04_pig_latin/pig_latin.rb
UTF-8
365
3.34375
3
[]
no_license
def translate(input) array = input.split('') result = [] array.each do |x| consonant = 0 len = x.length while((x[consonant] != 'a') && (x[consonant] != 'e') && (x[consonant] != 'i') && (x[consonant] != 'o')) consonant += 1 end result.push(x[consonant..(len - 1)] + x[-len..-(len - consonant + 1)] + "ay") end result.join(" ") end
true
f6f5e7e224d36047f505d1299c49e3e6276ac38d
Ruby
jackson-r/backend_prework
/day_6/exercises/person.rb
UTF-8
436
4.71875
5
[]
no_license
# Create a person class with at least 2 attributes and 2 behaviors. Call all # person methods below the class so that they print their result to the # terminal. class Person attr_accessor :thing1, :thing2 def initialize(thing1, thing2) @thing1 = thing1 @thing2 = thing2 end def method_one p self.thing1 end def method_two p self.thing2 end end me = Person.new("a", "b") me.method_one me.method_two
true
b9987a3fd8bea9a25e80a2cdb23ac099c10017b8
Ruby
roderickfung/quiz1
/q8.rb
UTF-8
1,407
4.03125
4
[]
no_license
# 8. Create a Ruby class called Article inside a module called Blog that has two attributes: title and body. Write another class called Snippet that inherits from the Article class. The Snippet method should return the same `title` but if you call `body` on a snippet object it should return the body truncated to a 100 characters with three dots at the end. This means if you create a snippet object and give it a body that has 200 characters, if you call the `body` method it should return the first 100 characters of that body and three dots at the end. If the body is 100 characters or less, it should not put three dots at the end. Include the module you built in question #7 in the Article class and use it when returning the title. # module HelperMethods def titleize(title) ignore = ["in","the","of","and","or","from"] title = title.split(" ").each{|i| i.capitalize! if ! ignore.include? i }.join(" ") end end module Blog class Article def initialize(title, body) @title = title @@body = body end extend HelperMethods end end attr_accessor :title attr_accessor :body class Snippit < Article Snippit.new.titleize(@@title) # @bd.length > 100 ? @bd = @bd[0..100] + "..." : @bd end title = "greetings people of the world" body = 200.times{|x| b << rand(/\w+\s/)}.join(//) article = HelperMethods::Blog.Article.new(t,b) p article.Snippit
true
df4c135b48a8e40899c4168d2e05df80e15aa249
Ruby
imwithsam/sales_engine
/lib/merchant.rb
UTF-8
2,220
2.671875
3
[]
no_license
require 'bigdecimal' require 'date' require_relative 'record' class Merchant < Record def name attributes[:name] end def items return @items if defined? @items @items = repository.engine.item_repository.find_all_by_merchant_id(id) end def invoices return @invoices if defined? @invoices @invoices = repository.engine.invoice_repository.find_all_by_merchant_id(id) end def paid_invoices return @paid_invoices if defined? @paid_invoices @paid_invoices = invoices.select(&:paid?) end def unpaid_invoices return @unpaid_invoices if defined? @unpaid_invoices @unpaid_invoices = invoices.reject(&:paid?) end def revenue(date = nil) @revenue ||= Hash.new do |h, key| h[key] = if key.is_a?(Date) paid_invoices.reduce(0) do |total, invoice| if invoice.created_at == key total + invoice.grand_total else total end end else paid_invoices.reduce(0) do |total, invoice| total + invoice.grand_total end end end @revenue[date] end def total_items_sold return @total_items_sold if defined? @total_items_sold item_sums = items.map do |item| item.invoice_items.reduce(0) do |sum, i| if repository.engine.invoice_repository.find_by_id(i.invoice_id).paid? sum + i.quantity else sum end end end @total_items_sold = item_sums.reduce(:+) end def favorite_customer return @favorite_customer if defined? @favorite_customer grouped_invoices = paid_invoices.group_by(&:customer_id) favorite_customer_id = grouped_invoices.sort_by { |k, v| v.count }.last[0] @favorite_customer = repository.engine.customer_repository .find_by_id(favorite_customer_id) end def customers_with_pending_invoices if defined? @customers_with_pending_invoices return @customers_with_pending_invoices end customers = unpaid_invoices.map do |invoice| repository.engine.customer_repository.find_by_id(invoice.customer_id) end @customers_with_pending_invoices = customers.uniq end end
true
0171493ff82db7a24c8eebf01160ad9f558a9421
Ruby
iastewar/oct-2015
/ruby/password_crack.rb
UTF-8
702
3.765625
4
[]
no_license
require 'digest/sha1' #finds original password given that it is n letters, lower case, and uses SHA1 hashing def find_password(hashed_password, n) password = ("a" * n).split(""); _find_password(hashed_password, password, 0) return password.join end def _find_password(hashed_password, password, index) if index >= password.length return false end for char in "a".."z" password[index] = char hash = Digest::SHA1.hexdigest(password.join) if (hash == hashed_password) return true end res = _find_password(hashed_password, password, index+1) if res return true end end return false end puts find_password("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", 5)
true
04ff3a14b460b80679079d6a8897af78a35dc619
Ruby
spemmons/zhivago_mr
/hour_counts.rb
UTF-8
927
2.640625
3
[]
no_license
#!/usr/bin/env ruby require 'rubygems' require 'wukong/script' module HourCounts class Mapper < Wukong::Streamer::Base def process(*args) imei,date,remainder = args[0].split(',') lat,lng,ign,spd,remainder = args[1].split(',') time = Time.parse(date) time_string = Time.gm(time.year,time.month,time.day,time.hour).strftime('%Y-%m-%d %H:%M') yield ign.to_i == 1 ? [time_string,1,0] : [time_string,0,1] end end class Reducer < Wukong::Streamer::AccumulatingReducer def start!(*args) @moving_count,@stopped_count = 0,0 end def accumulate(*args) key,moving,stopped,remainder = *args @moving_count += moving.to_i @stopped_count += stopped.to_i end def finalize minutes = Time.parse(key) yield [key,minutes.to_i / 60 / 60,@moving_count,@stopped_count] end end end Wukong.run(HourCounts::Mapper,HourCounts::Reducer)
true
3120abfdac672f2992e6e433b8dc207afbe83928
Ruby
amymcgowan/app_academy_open
/02_software_engineering_foundations/17_mastermind_project_2019/lib/code.rb
UTF-8
1,106
3.5
4
[]
no_license
class Code POSSIBLE_PEGS = { "R" => :red, "G" => :green, "B" => :blue, "Y" => :yellow } attr_reader :pegs def self.valid_pegs?(chars) chars.all? { |char| POSSIBLE_PEGS.has_key?(char.upcase) } end def self.random(length) random_pegs = [] length.times { random_pegs << POSSIBLE_PEGS.keys.sample } Code.new(Array.new(random_pegs)) end def self.from_string(string) Code.new(string.split("")) end def initialize(chars) if Code.valid_pegs?(chars) @pegs = chars.map(&:upcase) else raise "That is not a valid guess" end end def [](index) @pegs[index] end def length @pegs.length end def num_exact_matches(guess) sum = 0 (0...guess.length).each do |i| if guess[i] == @pegs[i] sum += 1 end end sum end def num_near_matches(guess) sum = 0 (0...guess.length).each do |i| if guess[i] != @pegs[i] && @pegs.include?(guess[i]) sum += 1 end end sum end def ==(other_code) other_code.pegs == self.pegs end end
true
648e6e1fe355e14480b0508a3e655ef02e9b8a71
Ruby
nataliarossini/DSA-challenges
/lec-84.rb
UTF-8
607
4.5625
5
[]
no_license
# Google Question # Given an array = [2,5,1,2,3,5,1,2,4]: # it should return 2 # Given an array = [2,1,1,2,3,5,1,2,4]: # ir should return 1 # Given an array = [2,3,4,5] # it should return undefined require 'set' def first_recurring_char(array) hash = Set.new array.each do |e| if hash.include?(e) return e else hash.add(e) end end nil end array = [2,5,1,2,3,5,1,2,4] # 2 array1 = [2,1,1,2,3,5,1,2,4] # 1 array2 = [2,3,4,5] # undefined / nil in ruby p first_recurring_char(array) p first_recurring_char(array1) p first_recurring_char(array2)
true
be6e2b2ff45179b047ec2d953797cbb16a97cd49
Ruby
fabianekc/HyvE4
/lib/tasks/sample_data.rake
UTF-8
1,863
2.65625
3
[]
no_license
namespace :db do desc "Fill database with sample data" task populate: :environment do make_users make_postings make_relationships make_projects make_groups make_structures make_datavals end end def make_users admin = User.create!(name: "Example User", email: "example@hyve.me", password: "foobar") admin.toggle!(:admin) 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(name: name, email: email, password: password) end end def make_postings users = User.all(limit: 6) 50.times do content = Faker::Lorem.sentence(5) users.each { |user| user.postings.create!(content: content) } end end def make_relationships users = User.all user = users.first followed_users = users[2..50] followers = users[3..40] followed_users.each { |followed| user.follow!(followed) } followers.each { |follower| follower.follow!(user) } end def make_projects users = User.all(limit: 15) 7.times do name = Faker::Company.name description = Faker::Lorem.sentence(20) users.each { |user| user.projects.create!(name: name, description: description) } end end def make_groups projects = Project.all(limit: 5) 6.times do |n| name = "Group #{n}" projects.each { |project| project.groups.create!(name: name) } end end def make_structures groups = Group.all 4.times do |n| name = "Item #{n}" groups.each { |group| group.structures.create!(name: name) } end end def make_datavals structures = Structure.all 10.times do |n| val = "0 1 2 3 4 5 6 7 8 9".split.shuffle.join[0...2] dat = n.days.from_now structures.each { |structure| structure.datavals.create!(valdatime: dat, value: val) } end end
true
15e8b0bca63eb9902bfa11f76e5955d0911c1205
Ruby
katsuyoshi/motion-support
/spec/motion-support/core_ext/time/conversion_spec.rb
UTF-8
1,535
2.71875
3
[ "MIT" ]
permissive
describe "Time" do describe "conversions" do describe "to_formatted_s" do before do @time = Time.utc(2005, 2, 21, 17, 44, 30.12345678901) end it "should use default conversion if no parameter is given" do @time.to_s.should == @time.to_default_s end it "should use default conversion if parameter is unknown" do @time.to_s(:doesnt_exist).should == @time.to_default_s end it "should convert to db format" do @time.to_s(:db).should == "2005-02-21 17:44:30" end it "should convert to short format" do @time.to_s(:short).should == "21 Feb 17:44" end it "should convert to time format" do @time.to_s(:time).should == "17:44" end it "should convert to number format" do @time.to_s(:number).should == "20050221174430" end it "should convert to nsec format" do @time.to_s(:nsec).should == "20050221174430123456789" end it "should convert to long format" do @time.to_s(:long).should == "February 21, 2005 17:44" end it "should convert to long_ordinal format" do @time.to_s(:long_ordinal).should == "February 21st, 2005 17:44" end end describe "custom date format" do it "should convert to custom format" do Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S' Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom).should == '20050221143000' Time::DATE_FORMATS.delete(:custom) end end end end
true
74a4e4e4e7e66d3782319c579ee246a86e8aa5d5
Ruby
ning/cosmic-standalone
/lib/jruby/1.9/gems/cinch-1.1.3/lib/cinch/logger/formatted_logger.rb
UTF-8
2,461
3
3
[ "MIT" ]
permissive
require "cinch/logger/logger" module Cinch module Logger # A formatted logger that will colorize individual parts of IRC # messages. class FormattedLogger < Cinch::Logger::Logger COLORS = { :reset => "\e[0m", :bold => "\e[1m", :red => "\e[31m", :green => "\e[32m", :yellow => "\e[33m", :blue => "\e[34m", } # @param [IO] output An IO to log to. def initialize(output = STDERR) @output = output @mutex = Mutex.new end # (see Logger::Logger#debug) def debug(messages) log(messages, :debug) end # (see Logger::Logger#log) def log(messages, kind = :generic) @mutex.synchronize do messages = [messages].flatten.map {|s| s.to_s.chomp} messages.each do |msg| message = Time.now.strftime("[%Y/%m/%d %H:%M:%S.%L] ") if kind == :debug prefix = colorize("!! ", :yellow) message << prefix + msg else pre, msg = msg.split(" :", 2) pre_parts = pre.split(" ") if kind == :incoming prefix = colorize(">> ", :green) if pre_parts.size == 1 pre_parts[0] = colorize(pre_parts[0], :bold) else pre_parts[0] = colorize(pre_parts[0], :blue) pre_parts[1] = colorize(pre_parts[1], :bold) end elsif kind == :outgoing prefix = colorize("<< ", :red) pre_parts[0] = colorize(pre_parts[0], :bold) end message << prefix + pre_parts.join(" ") message << colorize(" :#{msg}", :yellow) if msg end @output.puts message.encode("locale", {:invalid => :replace, :undef => :replace}) end end end # @api private # @param [String] text text to colorize # @param [Array<Symbol>] codes array of colors to apply # @return [String] colorized string def colorize(text, *codes) return text unless @output.tty? COLORS.values_at(*codes).join + text + COLORS[:reset] end # (see Logger::Logger#log_exception) def log_exception(e) lines = ["#{e.backtrace.first}: #{e.message} (#{e.class})"] lines.concat e.backtrace[1..-1].map {|s| "\t" + s} debug(lines) end end end end
true
c28c95458ad8d859d595ce5470deb20074f575cb
Ruby
Sameer164/Word-Ghost
/twoplayerversion/game.rb
UTF-8
2,718
3.640625
4
[]
no_license
require 'set' require_relative './player.rb' require 'byebug' FILE = File.open('text.txt') FILEDATA= FILE.readlines.map(&:chomp) SET = FILEDATA.to_set class Game attr_reader :dictionary, :current_player, :previous_player def initialize(name_player1, name_player2) @fragment = "" player1 = Player.new(name_player1) player2 = Player.new(name_player2) @players = [player1, player2] @dictionary = SET @current_player = @players[0] @previous_player = @players[-1] @hash = {} @players.each do |player| @hash[player.name] = "" end end def next_player! @players.rotate! @current_player = @players[0] @previous_player = @players[-1] end def valid_play?(str) alphabets = 'abcdefghijklmnopqrstuvwxyz' if !alphabets.include?(str) return false end curr_word = @fragment curr_word += str @dictionary.each do |word| if word.start_with?(curr_word) return true end end return false end def next_letter(name) letters = 'GHOST' last = @hash[name] if last.length == 0 return 'G' else return letters[letters.index(last[-1]) + 1] end end def take_turn(p) if @fragment.length == 0 puts "Start The Word #{p.name}" puts else puts "The word is #{@fragment}. Guess #{p.name} Guess" puts end input_letter = p.guess while !valid_play?(input_letter) p.alert_invalid_guess input_letter = p.guess end @fragment += input_letter puts "The word is #{@fragment}" puts if @dictionary.member?(@fragment) @hash[p.name] += next_letter(p.name) puts "#{@previous_player.name} has won this round." puts puts "#{p.name}: #{@hash[p.name]} #{@previous_player.name}: #{@hash[@previous_player.name]}" puts puts "Let's begin again" puts @fragment = "" end return false end def has_lost?(p) return @hash[p.name] == "GHOST" end def play_game while true take_turn(@current_player) next_player! if has_lost?(@previous_player) puts "#{@current_player.name} has won" puts break end end end end g = Game.new('sameer', 'samikshya') g.play_game
true
144f0a8d20e083831830c1c8abf6b8259d117003
Ruby
BenRKarl/WDI_work
/w01/d03/Andrea_Trapp/person.rb
UTF-8
557
3.796875
4
[]
no_license
require 'pry' class Person attr_reader :name attr_reader :age attr_accessor :fav_color attr_reader :fav_foods def initialize(name, age, fav_color, fav_foods) @name = name @age = age @fav_color = fav_color @fav_foods = fav_foods end def greeting puts "Hello #{@name}" end # this method would overwrite the attr_accessor # def fav_color=(color) # @fav_color = color # end end person1 = Person.new("Jim",34,"blue",["lasagne","pizza","hamburger"]) person2 = Person.new("Jane",35,"red", ["cheese cake", "garden salad"]) binding.pry
true
d5c913d78ad19b6f2f48d10fc69e06d4f16e233e
Ruby
doctordeep/arachni
/lib/arachni/mixins/progress_bar.rb
UTF-8
2,308
2.90625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
=begin Copyright 2010-2014 Tasos Laskos <tasos.laskos@gmail.com> 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. =end module Arachni module Mixins # # Progress bar and ETA methods # module ProgressBar # # Formats elapsed time to hour:min:sec # def format_time( t ) t = t.to_i rescue 0 sec = t % 60 min = ( t / 60 ) % 60 hour = t / 3600 sprintf( "%02d:%02d:%02d", hour, min, sec ) end # # Calculates ETA (Estimated Time of Arrival) based on current progress # and the start time of the operation. # # @param [Float] prog current progress percentage # @param [Time] start_time start time of the operation # # @return [String] ETA: hour:min:sec # def eta( prog, start_time ) @last_prog ||= prog @last_eta ||= "--:--:--" if @last_prog != prog elapsed = Time.now - start_time eta = elapsed * 100 / prog - elapsed eta_str = format_time( eta ) else eta_str = @last_eta prog = @last_prog end @last_prog = prog @last_eta = eta_str end # # Returns an ASCII progress bar based on the current progress percentage # # @param [Float] progress progress percentage # @param [Integer] width width of the progressbar in characters # # @return [String] 70% [=======> ] 100% # def progress_bar( progress, width = 100 ) progress = 100.0 if progress > 100 bar_prog = progress * width / 100 bar = '=' * ( bar_prog.ceil - 1 ).abs + '>' pad = ( width - bar_prog ) bar += ' ' * pad if pad > 0 "#{progress}% [#{bar}] 100% " end extend self end end end
true
1831ab4a722772e7225f4d7fbfd930aed16e5ae2
Ruby
james-poore/ruby_word_count
/wc.rb
UTF-8
5,705
3.125
3
[]
no_license
require 'optparse' require 'pp' APP_NAME = "wc.rb" APP_VERSION = "v1.0" APP_AUTHOR = "James L Poore Jr." DEBUG = false options = {} $text_from_stdin = false $names_from_stdin = false $error_message = "" optparse = OptionParser.new do |opts| opts.banner = "Usage: wc.rb [options] [file1 file2 ...]\n" + "\twc.rb [options] --files0-from=F\n\n" + "Options:\n" # Read in the options options[:bytes] = false opts.on('-c', '--bytes', 'Print the number of bytes in the file/s') do options[:bytes] = true end options[:chars] = false opts.on('-m', '--chars', 'Print the number of characters in the file/s') do options[:chars] = true end options[:lines] = false opts.on('-l', '--lines', 'Print the number of lines in the file/s') do options[:lines] = true end options[:words] = false opts.on('-w', '--words', 'Print the number of words in the file/s') do options[:words] = true end options[:max_line_length] = false opts.on('-L', '--max-line-length', 'Print the length of the longest line in the file/s') do options[:max_line_length] = true end options[:input_file] = nil opts.on('--files0-from=file_name', "Read input from the files specified by\n" + "\t\t\t\t\tNUL-terminated names in file file_name;\n" + "\t\t\t\t\tIf file_name is - then read names from standard input") do |file_name| if file_name == '-' $names_from_stdin = true options[:input_file] = $stdin else begin options[:input_file] = File.new(file_name, "r") rescue Exception => ex puts "An error of type #{ex.class} happened, message is #{ex.message}" end end end # This displays the version and exits opts.on('-v', '--version', 'Output the version of this app') do puts "#{APP_NAME} #{APP_VERSION}" puts "Copyright (c) 2015 #{APP_AUTHOR}" puts "" puts "Written by #{APP_AUTHOR}" exit end # This displays the help screen and exits. opts.on('--help', 'Display this screen' ) do puts "" puts "A Ruby implementation of the GNU coreutils wc command" puts "" puts opts exit end end def print_info(file_info) file_info.values.each do |value| print "\t#{value}" end puts "" end def get_bytes(file) File.size?(file) end def get_chars(file_text) num_of_chars = 0 num_of_chars = file_text.split("").length end def get_lines(file_text) lines = 0 lines = file_text.split("\n").length end def get_words(file_text) words = 0 words = file_text.split.length end def parse_file(file, options) file_info = {} file_text = file.read # If no options passed other than input file/s # print lines, words, and chars for each file options[:input_file].nil? if options.values.all? {|option| true ^ option} file_info[:lines] = get_lines(file_text) file_info[:words] = get_words(file_text) file_info[:chars] = get_chars(file_text) # Otherwise print only specified options else if options[:bytes] file_info[:bytes] = get_bytes(file) end if options[:chars] file_info[:chars] = get_chars(file_text) end if options[:words] file_info[:words] = get_words(file_text) end if options[:lines] file_info[:lines] = get_lines(file_text) end if options[:max_line_length] max_length = 0 file_text.split("\n").each do |line| length = line.length max_length = length if length > max_length end file_info[:max_line_length] = max_length end end file_info[:filename] = File.basename(file) unless $text_from_stdin return file_info end def load_file(file_name, sum_file_info, options) begin file = File.new(file_name.gsub("\n", ""), "r") file_info = parse_file(file, options) # Print output print_info(file_info) # Add new file to rolling sum file_info.keys.each do |key| sum_file_info[key] += file_info[key] unless key == (:filename || :max_line_length) if key == :max_line_length sum_file_info[key] = file_info[key] if file_info[key] > sum_file_info[key] end end rescue Exception => ex $error_message << "File '#{file_name}' could not be opened.\n" pp "An error of type #{ex.class} happened, message is #{ex.message}" if DEBUG pp ex.backtrace if DEBUG end return sum_file_info end # Begin main program # Read in options optparse.parse! sum_file_info = {} sum_file_info.default = 0 # wc.rb FILE if options[:input_file].nil? && !ARGV.empty? # Accept more than one file passed at the command line ARGV.each do |file_name| sum_file_info = load_file(file_name, sum_file_info, options) end # Only show sums if more than one file is passed in from the command line if ARGV.length > 1 sum_file_info[:total] = "total" print_info(sum_file_info) end puts $error_message unless $error_message.empty? # wc.rb --files0-from=FILE_NAME OR wc.rb --files0-from=- (stdin) elsif !options[:input_file].nil? # Either read lines from input file or read line of stdin for list of files files_list = options[:input_file].readlines # If file list came from stdin all file names are on one line...need to split files_list = files_list.first.split if $names_from_stdin files_list.each do |file_name| sum_file_info = load_file(file_name, sum_file_info, options) end # Print out sums if files_list.length > 1 sum_file_info[:total] = "total" print_info(sum_file_info) end puts $error_message unless $error_message.empty? # If stdin isn't empty read from there else $text_from_stdin = true file_info = parse_file($stdin, options) # Print output print_info(file_info) end
true
3a69fdd291b0a6eaacc8f717b43d75530160875d
Ruby
matthew-black/phase-0-tracks
/ruby/iteration.rb
UTF-8
2,920
4.375
4
[]
no_license
#RELEASE 0 def welcome_to_iteration name1 = "Matthew" name2 = "Bruno" puts "Welcome to iteration! The block has not yet ran." yield(name1, name2) puts "The block has run, hooray!" end welcome_to_iteration { |name1, name2| puts "#{name1} and #{name2} are learning about iteration!" } #RELEASE 1 pizza_toppings = ["sauce", "cheese", "meat", "veggies", "fruits"] types_of_toppings = { :cheese => "mozzarella, cheddar, parmeasan", :meat => "pepperoni, bacon, ham, sausage", :veggies => "jalapeno, onions, mushrooms", :fruits => "pineapple, strawberry, mango" } puts "pizza_toppings before .each: " p pizza_toppings puts "types_of_toppings before .each: " p types_of_toppings # make each topping all capital letters pizza_toppings.each do |toppings| p toppings.upcase end # permanently modify strings in the array pizza_toppings.map! do |toppings| toppings.upcase end p pizza_toppings # modify items in a hash types_of_toppings.each do |topping, topping_kinds| p topping.upcase p topping_kinds.upcase end puts "pizza_toppings after .map! (permanently changed)" p pizza_toppings puts "types_of_toppings after .each (not permanently changed)" p types_of_toppings #RELEASE 2 #1 delete_if permanently modifies an array words = ["tropical", "building", "street", "bake", "hi", "dictionary", "x-ray"] numbers = { :even => "2, 4, 6, 8, 10", :odd =>"1, 3, 5, 7, 9" } puts "#1" puts "Before delete_if: " p words p numbers words.delete_if { |word| word.length > 4} numbers.delete_if { |type_of_number, number| type_of_number == :even} puts "After delete_if:" p words p numbers puts " " #2 keep_if permanently modifies and array words = ["tropical", "building", "street", "bake", "hi", "dictionary", "x-ray"] numbers = { :even => "2, 4, 6, 8, 10", :odd =>"1, 3, 5, 7, 9" } puts "#2" puts "Before keep_if: " p words p numbers words.keep_if { |word| word.length > 4} numbers.keep_if { |type_of_number, number| type_of_number == :even} puts "After keep_if: " p words p numbers puts " " #3 reject does not permanently modify an array, so added the # bang operator to make the reject method's effect more clear words = ["tropical", "building", "street", "bake", "hi", "dictionary", "x-ray"] numbers = { :even => "2, 4, 6, 8, 10", :odd =>"1, 3, 5, 7, 9" } puts "#3" puts "Before reject!: " p words p numbers words.reject! { |word| word.length < 5 } numbers.reject! { |type_of_number, number| type_of_number == :even} puts "After reject!: " p words p numbers puts " " #4 drop_while does not permantly modify an array, and the bang operator # doesn't apply, so added in an extra printout of drop_while doing it's # fun little method words = ["tropical", "building", "street", "bake", "hi", "dictionary", "x-ray"] puts "#4" puts "Before drop_while: " p words puts "'During' drop_while: " p words.drop_while { |word| word.length > 3} puts "After drop_while: " p words
true
3cfcca810f73e87a034f5312323e317762211f73
Ruby
ansdelft/qti
/lib/qti/v1/models/interactions/base_fill_blank_interaction.rb
UTF-8
1,428
2.59375
3
[ "MIT" ]
permissive
module Qti module V1 module Models module Interactions class BaseFillBlankInteraction < BaseInteraction CANVAS_REGEX ||= /(\[.+?\])/.freeze def canvas_stem_items(item_prompt) item_prompt.split(CANVAS_REGEX).map.with_index do |stem_item, index| if stem_item.match CANVAS_REGEX # Strip the brackets before searching stem_blank(index, canvas_blank_id(stem_item[1..-2])) else stem_text(index, stem_item) end end end def stem_blank(index, value) { id: "stem_#{index}", position: index + 1, type: 'blank', blank_id: value } end def stem_text(index, value) { id: "stem_#{index}", position: index + 1, type: 'text', value: value } end def canvas_blank_id(stem_item) blank_id = nil node.xpath('.//xmlns:response_lid/xmlns:material').children.map do |response_lid_node| if stem_item == response_lid_node.text blank_id = response_lid_node.ancestors('response_lid').first.attributes['ident']&.value end end blank_id end end end end end end
true
b9a9244b44aec0a203b28e84e2dac95137bdc9e4
Ruby
peterallin/palaver
/lib/palaver/gauge.rb
UTF-8
666
2.671875
3
[ "BSD-2-Clause" ]
permissive
# Copyright (c) 2012, Peter Allin <peter@peca.dk> All rights reserved. # See LICENSE file for licensing information. module Palaver class Gauge < Palaver::Base def initialize(options) @inital_percentage = 0 super(options) end def show cmd = "dialog #@common_options --gauge '#@text' #@height #@width #@inital_percentage" @pipe = IO.popen(cmd,"w") end def percentage(p) if @pipe then @pipe.puts p else @inital_percentage = p end end def close @pipe.close end private def inital_percentage(percentage) @inital_percentage = percentage end end end
true
7ee7cedd6baf9812d97f45f4fd76803b76a52531
Ruby
gerndtr/ruby_practice
/Ruby_book/chapt7_1.rb
UTF-8
146
3.0625
3
[]
no_license
puts 1 < 2 puts 1 > 2 puts 4 >= 5 puts 5 <= 5 puts "bug lady" < "Xander" puts "bug lady".downcase < "Xander".downcase puts 2 < 10 puts "2" < "10"
true
b62c379e5bbcde5bb83c9f86931aa136131c46e8
Ruby
andresjordanze/ray_tracing
/vector3d.rb
UTF-8
916
3.484375
3
[]
no_license
class Vector3d attr_accessor :x, :y, :z def initialize(x,y,z) @x = x @y = y @z = z end def sum(v2) x = (@x + v2.x) y = (@y + v2.y) z = (@z + v2.z) r = Vector3d.new(x,y,z) end def res(v2) x = (@x - v2.x) y = (@y - v2.y) z = (@z - v2.z) r = Vector3d.new(x,y,z) end def esc(v2) r = (@x * v2.x)+(@y * v2.y)+(@z * v2.z) end def vec(v2) x = (@y * v2.z)-(v2.y * @z) y = (@z * v2.x)-(v2.z * @x) z = (@x * v2.y)-(v2.x * @y) r = Vector3d.new(x,y,z) end def mod r = Math.sqrt((@x**2)+(@y**2)+(@z**2)) end def prod(n) x = @x*n y = @y*n z = @z*n r = Vector3d.new(x,y,z) end def div(n) num = n.to_f x = @x * (1 / num) y = @y * (1 / num) z = @z * (1 / num) r = Vector3d.new(x,y,z) end def sum1(n) x = @x + n y = @y + n z = @z + n r = Vector3d.new(x,y,z) end end
true
d68d5ba515bc3272adbbabe04260637134eb5f34
Ruby
Shehbaz/prima
/lib/prima.rb
UTF-8
270
2.75
3
[]
no_license
require 'prima/primegen' require 'prima/table' module Prima class Prima attr_accessor :length,:algorithm def initialize(length,algo = Primegen.new) @algorithm = algo @length = length end def generate algorithm.generate(length) end end end
true
5bb352c51ca7ec33c3421986380c893880043b21
Ruby
torihuang/phase-0
/week-4/mini-challenge.rb
UTF-8
402
4.03125
4
[ "MIT" ]
permissive
valueNotEntered = true; while valueNotEntered do puts "Is it a leap year? Y/N" isLeapYear = gets.chomp if isLeapYear == "N" puts "There are #{365*24} hours in a year." valueNotEntered = false; elsif isLeapYear == "Y" puts "There are #{366*24} hours in a leap year." valueNotEntered = false; else puts "Invalid input. Answer must be Y/N. Is it a leap year? Y/N" end end
true
e237c6f8a73f1b380a0f5703b88d2846dac2e173
Ruby
lishulongVI/leetcode
/ruby/41.First Missing Positive(缺失的第一个正数).rb
UTF-8
1,506
3.796875
4
[ "MIT" ]
permissive
=begin <p>Given an unsorted integer array, find the smallest missing&nbsp;positive integer.</p> <p><strong>Example 1:</strong></p> <pre> Input: [1,2,0] Output: 3 </pre> <p><strong>Example 2:</strong></p> <pre> Input: [3,4,-1,1] Output: 2 </pre> <p><strong>Example 3:</strong></p> <pre> Input: [7,8,9,11,12] Output: 1 </pre> <p><strong>Note:</strong></p> <p>Your algorithm should run in <em>O</em>(<em>n</em>) time and uses constant extra space.</p> <p>给定一个未排序的整数数组,找出其中没有出现的最小的正整数。</p> <p><strong>示例&nbsp;1:</strong></p> <pre>输入: [1,2,0] 输出: 3 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre>输入: [3,4,-1,1] 输出: 2 </pre> <p><strong>示例&nbsp;3:</strong></p> <pre>输入: [7,8,9,11,12] 输出: 1 </pre> <p><strong>说明:</strong></p> <p>你的算法的时间复杂度应为O(<em>n</em>),并且只能使用常数级别的空间。</p> <p>给定一个未排序的整数数组,找出其中没有出现的最小的正整数。</p> <p><strong>示例&nbsp;1:</strong></p> <pre>输入: [1,2,0] 输出: 3 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre>输入: [3,4,-1,1] 输出: 2 </pre> <p><strong>示例&nbsp;3:</strong></p> <pre>输入: [7,8,9,11,12] 输出: 1 </pre> <p><strong>说明:</strong></p> <p>你的算法的时间复杂度应为O(<em>n</em>),并且只能使用常数级别的空间。</p> =end # @param {Integer[]} nums # @return {Integer} def first_missing_positive(nums) end
true
b3a3a6ba0258ff57255d942177c2c4fc16e95fe6
Ruby
adrientoub/gdpr-explorer
/videos/types.rb
UTF-8
1,300
2.828125
3
[]
no_license
require 'json' require 'date' class VideosIndex attr_accessor :version, :channels def self.from_json(json) index = new index.version = json['version'] index.channels = json['channels']&.map do |channel| ChannelIndex.from_json(channel) end index end end class ChannelIndex attr_accessor :channel_name, :channel_url, :path, :view_count def self.from_json(json) channel = new channel.channel_name = json['channel_name'] channel.channel_url = json['channel_url'] channel.path = json['path'] channel.view_count = json['view_count'] channel end def load_channel(output_path) content = File.read(File.join(output_path, self.path)) json = JSON.parse(content) ChannelFile.from_json(json) end end class ChannelFile attr_accessor :channel_name, :channel_url, :views def self.from_json(json) channel = new channel.channel_name = json['channel_name'] channel.channel_url = json['channel_url'] channel.views = json['views'].map do |view| View.from_json(view) end channel end end class View attr_accessor :url, :title, :date def self.from_json(json) view = new view.url = json['url'] view.title = json['titlee'] view.date = DateTime.parse(json['date']) view end end
true
cfd504a7378bb1f6a6461c8c36b9a91b7a00c1aa
Ruby
colleenlavin/joerickettssucks
/scrapper.rb
UTF-8
373
2.890625
3
[]
no_license
# TwitterTrends1.rb require 'rubygems' require 'rest_client' require "uri" def getPage(page) offset = (50 * page).to_s url = 'http://archive.is/offset=' + offset + '/http://laist.com/*' RestClient.get(url) end page = getPage(0) for url in URI.extract(page) if url.include? 'laist' puts url end end # => ["http://foo.example.org/bla", "mailto:test@example.com"]
true
52d1b06a9f527fc32a43c638f7c264a9c994c3f6
Ruby
DragonRuby/dragonruby-game-toolkit-contrib
/dragon/readme_docs.rb
UTF-8
60,526
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
# coding: utf-8 # Copyright 2019 DragonRuby LLC # MIT License # readme_docs.rb has been released under MIT (*only this file*). module GTK module ReadMeDocs def docs_method_sort_order %i[ docs_hello_world docs_new_project docs_deployment docs_deployment_mobile docs_deployment_steam docs_dragonruby_philosophy docs_faq docs_ticks_and_frames docs_sprites docs_labels docs_sounds docs_game_state docs_accessing_files docs_troubleshooting_performance ] end def docs_hello_world <<-S * Welcome Welcome to DragonRuby Game Toolkit! The information contained here is all available in your the zip file at ~./docs/docs.html~. You can browse the docs in a local website by starting up DragonRuby and going to ~http://localhost:9001~. * Community Our Discord server is extremely supportive and helpful. It's the best place to get answers to your questions. The developers of DragonRuby are also on this server if you have any feedback or bug reports. The Link to Our Discord Server is: [[http://discord.dragonruby.org]]. The News Letter will keep you in the loop with regards to current DragonRuby Events: [[http://dragonrubydispatch.com]]. * Book Brett Chalupa (one of our community members) has written a book to help you get started: [[https://book.dragonriders.community/]] * Tutorial Video Here are some videos to help you get the lay of the land. 1. Building Tetris - Part 1: [[https://youtu.be/xZMwRSbC4rY]] 2. Building Tetris - Part 2: [[https://youtu.be/C3LLzDUDgz4]] * Getting Started Tutorial This is a tutorial written by Ryan C Gordon (a Juggernaut in the industry who has contracted to Valve, Epic, Activision, and EA... check out his Wikipedia page: [[https://en.wikipedia.org/wiki/Ryan_C._Gordon]]). ** Introduction Welcome! Here's just a little push to get you started if you're new to programming or game development. If you want to write a game, it's no different than writing any other program for any other framework: there are a few simple rules that might be new to you, but more or less programming is programming no matter what you are building. Did you not know that? Did you think you couldn't write a game because you're a "web guy" or you're writing Java at a desk job? Stop letting people tell you that you can't, because you already have everything you need. Here, we're going to be programming in a language called "Ruby." In the interest of full disclosure, I (Ryan Gordon) wrote the C parts of this toolkit and Ruby looks a little strange to me (Amir Rajan wrote the Ruby parts, discounting the parts I mangled), but I'm going to walk you through the basics because we're all learning together, and if you mostly think of yourself as someone that writes C (or C++, C#, Objective-C), PHP, or Java, then you're only a step behind me right now. ** Prerequisites Here's the most important thing you should know: Ruby lets you do some complicated things really easily, and you can learn that stuff later. I'm going to show you one or two cool tricks, but that's all. Do you know what an if statement is? A for-loop? An array? That's all you'll need to start. ** The Game Loop Ok, here are few rules with regards to game development with GTK: - Your game is all going to happen under one function ... - that runs 60 times a second ... - and has to tell the computer what to draw each time. That's an entire video game in one run-on sentence. Here's that function. You're going to want to put this in mygame/app/main.rb, because that's where we'll look for it by default. Load it up in your favorite text editor. #+begin_src ruby def tick args args.outputs.labels << [580, 400, 'Hello World!'] end #+end_src Now run ~dragonruby~ ...did you get a window with "Hello World!" written in it? Good, you're officially a game developer! ** Breakdown Of The ~tick~ Method ~mygame/app/main.rb~, is where the Ruby source code is located. This looks a little strange, so I'll break it down line by line. In Ruby, a '#' character starts a single-line comment, so I'll talk about this inline. #+begin_src ruby # This "def"ines a function, named "tick," which takes a single argument # named "args". DragonRuby looks for this function and calls it every # frame, 60 times a second. "args" is a magic structure with lots of # information in it. You can set variables in there for your own game state, # and every frame it will updated if keys are pressed, joysticks moved, # mice clicked, etc. def tick args # One of the things in "args" is the "outputs" object that your game uses # to draw things. Afraid of rendering APIs? No problem. In DragonRuby, # you use arrays to draw things and we figure out the details. # If you want to draw text on the screen, you give it an array (the thing # in the [ brackets ]), with an X and Y coordinate and the text to draw. # The "<<" thing says "append this array onto the list of them at # args.outputs.labels) args.outputs.labels << [580, 400, 'Hello World!'] end #+end_src Once your ~tick~ function finishes, we look at all the arrays you made and figure out how to draw it. You don't need to know about graphics APIs. You're just setting up some arrays! DragonRuby clears out these arrays every frame, so you just need to add what you need _right now_ each time. ** Rendering A Sprite Now let's spice this up a little. We're going to add some graphics. Each 2D image in DragonRuby is called a "sprite," and to use them, you just make sure they exist in a reasonable file format (png, jpg, gif, bmp, etc) and specify them by filename. The first time you use one, DragonRuby will load it and keep it in video memory for fast access in the future. If you use a filename that doesn't exist, you get a fun checkerboard pattern! There's a "dragonruby.png" file included, just to get you started. Let's have it draw every frame with our text: #+begin_src ruby def tick args args.outputs.labels << [580, 400, 'Hello World!'] args.outputs.sprites << [576, 100, 128, 101, 'dragonruby.png'] end #+end_src (Pro Tip: you don't have to restart DragonRuby to test your changes; when you save main.rb, DragonRuby will notice and reload your program.) That ~.sprites~ line says "add a sprite to the list of sprites we're drawing, and draw it at position (576, 100) at a size of 128x101 pixels". You can find the image to draw at dragonruby.png. ** Coordinate System and Virtual Canvas Quick note about coordinates: (0, 0) is the bottom left corner of the screen, and positive numbers go up and to the right. This is more "geometrically correct," even if it's not how you remember doing 2D graphics, but we chose this for a simpler reason: when you're making Super Mario Brothers and you want Mario to jump, you should be able to add to Mario's y position as he goes up and subtract as he falls. It makes things easier to understand. Also: your game screen is _always_ 1280x720 pixels. If you resize the window, we will scale and letterbox everything appropriately, so you never have to worry about different resolutions. Ok, now we have an image on the screen, let's animate it: #+begin_src ruby def tick args args.state.rotation ||= 0 args.outputs.labels << [580, 400, 'Hello World!' ] args.outputs.sprites << [576, 100, 128, 101, 'dragonruby.png', args.state.rotation] args.state.rotation -= 1 end #+end_src Now you can see that this function is getting called a lot! ** Game State Here's a fun Ruby thing: ~args.state.rotation ||= 0~ is shorthand for "if args.state.rotation isn't initialized, set it to zero." It's a nice way to embed your initialization code right next to where you need the variable. ~args.state~ is a place you can hang your own data. It's an open data structure that allows you to define properties that are arbitrarily nested. You don't need to define any kind of class. In this case, the current rotation of our sprite, which is happily spinning at 60 frames per second. If you don't specify rotation (or alpha, or color modulation, or a source rectangle, etc), DragonRuby picks a reasonable default, and the array is ordered by the most likely things you need to tell us: position, size, name. ** There Is No Delta Time One thing we decided to do in DragonRuby is not make you worry about delta time: your function runs at 60 frames per second (about 16 milliseconds) and that's that. Having to worry about framerate is something massive triple-AAA games do, but for fun little 2D games? You'd have to work really hard to not hit 60fps. All your drawing is happening on a GPU designed to run Fortnite quickly; it can definitely handle this. Since we didn't make you worry about delta time, you can just move the rotation by 1 every time and it works without you having to keep track of time and math. Want it to move faster? Subtract 2. ** Handling User Input Now, let's move that image around. #+begin_src ruby def tick args args.state.rotation ||= 0 args.state.x ||= 576 args.state.y ||= 100 if args.inputs.mouse.click args.state.x = args.inputs.mouse.click.point.x - 64 args.state.y = args.inputs.mouse.click.point.y - 50 end args.outputs.labels << [580, 400, 'Hello World!'] args.outputs.sprites << [args.state.x, args.state.y, 128, 101, 'dragonruby.png', args.state.rotation] args.state.rotation -= 1 end #+end_src Everywhere you click your mouse, the image moves there. We set a default location for it with ~args.state.x ||= 576~, and then we change those variables when we see the mouse button in action. You can get at the keyboard and game controllers in similar ways. ** Coding On A Raspberry Pi We have only tested DragonRuby on a Raspberry Pi 3, Models B and B+, but we believe it _should_ work on any model with comparable specs. If you're running DragonRuby Game Toolkit on a Raspberry Pi, or trying to run a game made with the Toolkit on a Raspberry Pi, and it's really really slow-- like one frame every few seconds--then there's likely a simple fix. You're probably running a desktop environment: menus, apps, web browsers, etc. This is okay! Launch the terminal app and type: #+begin_src sudo raspi-config #+end_src It'll ask you for your password (if you don't know, try "raspberry"), and then give you a menu of options. Find your way to "Advanced Options", then "GL Driver", and change this to "GL (Full KMS)" ... not "fake KMS," which is also listed there. Save and reboot. In theory, this should fix the problem. If you're _still_ having problems and have a Raspberry Pi 2 or better, go back to raspi-config and head over to "Advanced Options", "Memory split," and give the GPU 256 megabytes. You might be able to avoid this for simple games, as this takes RAM away from the system and reserves it for graphics. You can also try 128 megabytes as a gentler option. Note that you can also run DragonRuby without X11 at all: if you run it from a virtual terminal it will render fullscreen and won't need the "Full KMS" option. This might be attractive if you want to use it as a game console sort of thing, or develop over ssh, or launch it from RetroPie, etc. ** Conclusion There is a lot more you can do with DragonRuby, but now you've already got just about everything you need to make a simple game. After all, even the most fancy games are just creating objects and moving them around. Experiment a little. Add a few more things and have them interact in small ways. Want something to go away? Just don't add it to ~args.output~ anymore. S end def docs_new_project <<-S * Starting a New DragonRuby Project The DragonRuby zip that contains the engine is a complete, self contained project structure. To create a new project, unzip the zip file again in its entirety and use that as a starting point for another game. This is the recommended approach to starting a new project. ** Considerations For Public Git Repositories You can open source your game's code given the following options. *** Option 1 (Recommended) Your public repository needs only to contain the contents of ~./mygame~. This approach is the cleanest and doesn't require your ~.gitignore~ to be polluted with DragonRuby specific files. *** Option 2 (Restrictions Apply) IMPORTANT: Do NOT commit ~dragonruby-publish(.exe)~, or ~dragonruby-bind(.exe)~. #+begin_src dragonruby dragonruby.exe dragonruby-publish dragonruby-publish.exe dragonruby-bind dragonruby-bind.exe /tmp/ /builds/ /logs/ /samples/ /docs/ /.dragonruby/ #+end_src If you'd like people who do not own a DragonRuby license to run your game, you may include the ~dragonruby(.exe)~ binary within the repo. This permission is granted in good-faith and can be revoked if abused. ** Considerations For Private Git Repos The following ~.gitignore~ should be used for private repositories (commercial games). #+begin_src /tmp/ /logs/ #+end_src You'll notice that everything else is committed to source control (even the ~./builds~ directory). The DragonRuby binary/package is designed to be committed in its entirety with your source code (it’s why we keep it small). This protects the “shelf life” for commercial games. 3 years from now, we might be on a vastly different version of the engine. But you know that the code you’ve written will definitely work with the version that was committed to source control. For private repositories, it's strongly recommended that you do NOT keep DragonRuby Game Toolkit in a shared location and instead unzip a clean copy for every game (and commit everything to source control). IMPORTANT: File access functions are sandoxed and assume that the ~dragonruby~ binary lives alongside the game you are building. Do not expect file access functions to return correct values if you are attempting to run the ~dragonruby~ binary from a shared location. It's recommended that the directory structure contained in the zip is not altered and games are built using that starter template. S end def docs_deployment <<-S * Deploying To Itch.io Once you've built your game, you're all set to deploy! Good luck in your game dev journey and if you get stuck, come to the Discord channel! ** Creating Your Game Landing Page Log into Itch.io and go to [[https://itch.io/game/new]]. - Title: Give your game a Title. This value represents your `gametitle`. - Project URL: Set your project url. This value represents your `gameid`. - Classification: Keep this as Game. - Kind of Project: Select HTML from the drop down list. Don't worry, the HTML project type _also supports binary downloads_. - Uploads: Skip this section for now. You can fill out all the other options later. ** Update Your Game's Metadata Point your text editor at mygame/metadata/game_metadata.txt and make it look like this: NOTE: Remove the ~#~ at the beginning of each line. #+begin_src devid=bob devtitle=Bob The Game Developer gameid=mygame gametitle=My Game version=0.1 #+end_src The ~devid~ property is the username you use to log into Itch.io. The ~devtitle~ is your name or company name (it can contain spaces). The ~gameid~ is the Project URL value. The ~gametitle~ is the name of your game (it can contain spaces). The ~version~ can be any ~major.minor~ number format. ** Building Your Game For Distribution Open up the terminal and run this from the command line: #+begin_src ./dragonruby-publish --only-package mygame #+end_src (if you're on Windows, don't put the "./" on the front. That's a Mac and Linux thing.) A directory called ~./build~ will be created that contains your binaries. You can upload this to Itch.io manually. *** Browser Game Settings For the HTML version of your game, the following configuration is required for your game to run correctly: - Check the checkbox labeled ~This file will be played in the browser~ for the html version of your game (it's one of the zip files you'll upload). - Ensure that ~Embed options -> SharedArrayBuffer support~ is checked. - Be sure to set the ~Viewport dimensions~ to ~1280x720~ for landscape games or your game will not be positioned correctly on your Itch.io page. - Be sure to set the ~Viewport dimensions~ to ~540x960~ for portrait games or your game will not be positioned correctly on your Itch.io page. For subsequent updates you can use an automated deployment to Itch.io: #+begin_src ./dragonruby-publish mygame #+end_src DragonRuby will package _and publish_ your game to itch.io! Tell your friends to go to your game's very own webpage and buy it! If you make changes to your game, just re-run dragonruby-publish and it'll update the downloads for you. *** Consider Adding Pause When Game is In Background It's a good idea to pause the game if it doesn't have focus. Here's an example of how to do that #+begin_src def tick args # if the keyboard doesn't have focus, and the game is in production mode, and it isn't the first tick if !args.inputs.keyboard.has_focus && args.gtk.production && args.state.tick_count != 0 args.outputs.background_color = [0, 0, 0] args.outputs.labels << { x: 640, y: 360, text: "Game Paused (click to resume).", alignment_enum: 1, r: 255, g: 255, b: 255 } # consider setting all audio volume to 0.0 else # perform your regular tick function end end #+end_src If you want your game to run at full speed even when it's in the background, add the following line to ~mygame/metadata/cvars.txt~: #+begin_src renderer.background_sleep=0 #+end_src *** Consider Adding a Request to Review Your Game In-Game Getting reviews of your game are extremely important and it's recommended that you put an option to review within the game itself. You can use ~args.gtk.open_url~ plus a review URL. Here's an example: #+begin_src def tick args # render the review button args.state.review_button ||= { x: 640 - 50, y: 360 - 25, w: 100, h: 50, path: :pixel, r: 0, g: 0, b: 0 } args.outputs.sprites << args.state.review_button args.outputs.labels << { x: 640, y: 360, anchor_x: 0.5, anchor_y: 0.5, text: "Review" } # check to see if the review button was clicked if args.inputs.mouse.intersect_rect? args.state.review_button # open platform specific review urls if args.gtk.platform? :ios # your app id is provided at Apple's Developer Portal (numeric value) args.gtk.openurl "itms-apps://itunes.apple.com/app/idYOURGAMEID?action=write-review" elsif args.gtk.platform? :android # your app id is the name of your android package args.gtk.openurl ""https://play.google.com/store/apps/details?id=YOURGAMEID" elsif args.gtk.platform? :web # if they are playing the web version of the game, take them to the purchase page on itch args.gtk.openurl "https://amirrajan.itch.io/YOURGAMEID/purchase" else # if they are playing the desktop version of the game, take them to itch's rating page args.gtk.openurl "https://amirrajan.itch.io/YOURGAMEID/rate?source=game" end end end #+end_src S end def docs_deployment_mobile <<-S * Deploying To Mobile Devices If you have a Pro subscription, you also have the capability to deploy to mobile devices. ** Deploying to iOS To deploy to iOS, you need to have a Mac running MacOS Catalina, an iOS device, and an active/paid Developer Account with Apple. From the Console type: ~$wizards.ios.start~ and you will be guided through the deployment process. - ~$wizards.ios.start env: :dev~ will deploy to an iOS device connected via USB. - ~$wizards.ios.start env: :hotload~ will deploy to an iOS device connected via USB with hotload enabled. - ~$wizards.ios.start env: :sim~ will deploy to the iOS simulator. - ~$wizards.ios.start env: :prod~ will package your game for distribution via Apple's AppStore. ** Deploying to Android To deploy to Android, you need to have an Android emulator/device, and an environment that is able to run Android SDK. ~dragonruby-publish~ will create an APK for you. From there, you can sign the APK and install it to your device. The signing and installation procedure varies from OS to OS. Here's an example of what the command might look like: #+begin_src # generating a keystore keytool -genkey -v -keystore APP.keystore -alias mygame -keyalg RSA -keysize 2048 -validity 10000 # deploying to a local device/emulator apksigner sign --ks mygame.keystore mygame-android.apk adb install mygame-android.apk # read logs of device adb logcat -e mygame # signing for Google Play apksigner sign --min-sdk-version 21 --ks ./profiles/APP.keystore ./builds/APP-googleplay.aab #+end_src S end def docs_deployment_steam <<-S * Deploying To Steam If you have a Indie or Pro subscription, you also get streamlined deployment to Steam via ~dragonruby-publish~. Please note that games developed using the Standard license can deploy to Steam using the Steamworks toolchain [[https://partner.steamgames.com/doc/store/releasing]]. ** Testing on Your Steam Deck *** Easy Setup 1. Run ~dragonruby-publish --only-package~. 2. Find the Linux build of your game under the ~./builds~ directory and load it onto an SD Card. 3. Restart the Steam Deck in Desktop Mode. 4. Copy your game binary onto an SD card. 5. Find the game on the SD card and double click binary. *** Advanced Setup 1. Restart the Steam Deck in Desktop Mode. 2. Open up Konsole and set an admin password via ~passwd~. 3. Disable readonly mode: ~sudo steamos-readonly disable~. 4. Update pacman ~sudo pacman-key --populate archlinux~. 5. Update sshd_config ~sudo vim /etc/ssh/sshd_config~ and uncomment the ~PubkeyAuthentication yes~ line. 6. Enable ssh: ~sudo systemctl enable sshd~. 7. Start ssh: ~sudo systemctl start sshd~. 8. Run ~dragonruby-publish --only-package~. 9. Use ~scp~ to copy the game over from your dev machine without needing an SD Card: ~scp -R ./builds/SOURCE.bin deck@IP_ADDRESS:/home/deck/Downloads~ Note: Steps 2 through 7 need only be done once. Note: ~scp~ comes pre-installed on Mac and Linux. You can download the tool for Windows from [[https://winscp.net/eng/index.php]] ** Setting up the game on the Partner Site *** Getting your App ID You'll need to create a product on Steam. This is unfortunately manual and requires identity verification for taxation purposes. Valve offers pretty robust documentation on all this, though. Eventually, you'll have an App ID for your game. Go to https://partner.steamgames.com/apps/view/$APPID, where $APPID is your game's App ID. *** Specifing Supported Operating Systems for your game Find the "Supported Operating Systems" section and make sure these things are checked: - Windows: 64 Bit Only - macOS: 64 Bit (Intel) and Apple Silicon - Linux: Including SteamOS Click the "Save" button below it. *** Setting up SteamPipe Depots Click the "SteamPipe" tab at the top of the page, click on "depots" Click the "Add a new depot" button. Give it a name like "My Game Name Linux Depot" and take whatever depot ID it offers you. You'll see this new depot is listed on the page now. Fix its settings: - Language: All Languages - For DLC: Base App - Operating System: Linux + SteamOS - Architecture: 64-bit OS only - Platform: All Do this again, make a "My Game Name Windows Depot", set it to the same things, except "Operating System," which should be "Windows," of course. Do this again, make a "My Game Name Mac Depot", set it to the same things, except "Operating System," which should be "macOS," of course. Push the big green "Save" button on the page. Now we have a place to upload platform-specific builds of your game. *** Setting up Launch Options Click on the "Installation" tab near the top of the page, then "General Installation". Under "Launch Options," click the "Add new launch option" button, edit the new section that just popped up, and set it like this: (Whenever you see "mygamename" in here, this should be whatever your game_metadata's "gameid" value is set to. If you see "My Game Name", it's whatever your game_metadata's "gametitle" value is set to, but you'll have to check in case we mangled it to work as a filename.) - Executable: mygamename.exe - Launch Type: Launch (Default) - Operating System: Windows - CPU Architecture: 64-bit only - Everything else can be default/blank. Click the "Update" button on that section. Add another launch option, as before: - Executable: My Game Name.app - Launch Type: Launch (Default) - Operating System: macOS Add another launch option, as before: - Executable: mygamename - Launch Type: Launch (Default) - Operating System: Linux + SteamOS - CPU Architecture: 64-bit only *** Publish Changes Go to the "Publish" tab at near the top of the page. Click the "View Diffs" button and make sure it looks sane (it should just be the things we've changed in here), then click "Prepare for Publishing", then "Publish to Steam" and follow the instructions to publish these changes. Go to https://partner.steamgames.com/apps/associated/$APPID For each package, make sure all three depots are included. ** Configuring ~dragonruby-publish~ You only have to do this part once when first setting up your game. Note that this capability is only available for Indie and Pro license tiers. If you have a Standard DragonRuby License, you'll need to use the Steamworks toolchains directly. Go add a text file to your game's ~metadata~ directory called ~steam_metadata.txt~ ... note that this file will be filtered out ~dragonruby-publish~ packages the game and will not be distributed with the published game. #+begin_src steam.publish=true steam.branch=public steam.username=AAA steam.appid=BBB steam.linux_depotid=CCC steam.windows_depotid=DDD steam.mac_depotid=EEE #+end_src If steam.publish is set to ~false~ then dragonruby-publish will not attempt to upload to Steam. ~false~ is the default if this file, or this setting, is missing. Where "AAA" is the login name on the Steamworks Partner Site to use for publishing builds, "BBB" is your game-specific AppID provided by Steam, "CCC", "DDD", and "EEE" are the DepotIDs you created for Linux, Windows, and macOS builds, respectively. *** Setting a branch live Once your build is uploaded, you can assign it to a specific branch through the interface on the Partner site. You can make arbitrary branches here, like "beta" or "nightly" or "fixing-weird-bug" or whatever. The one that goes to the end users without them switching branches, is "default" and you should assume this is where paying customers live, so be careful before you set a build live there. You can have dragonruby-publish set the builds it publishes live on a branch immediately, if you prefer. Simply add... #+begin_src steam.branch=XXX #+end_src ...to steam_metadata.txt, where "XXX" is the branch name from the partner website. If this is blank or unspecified, it will _not_ set the build live on _any_ branch. Setting the value to ~public~ will push to production. A reasonable strategy is to create a (possibly passworded) branch called "staging" and have dragonruby-publish always push to there automatically. Then you can test from a Steam install, pushing as often as you like, and when you are satisfied, manually set the latest build live on default for the general public to download. If you are feeling brave, you can always just set all published builds live on default, too. After all, if you break it, you can always just push a fix right away. :) (or use the Partner Site to roll back to a known-good build, you know.) ** Publishing Build Run dragonuby-publish as you normally would. When it is time to publish to Steam, it will set up any tools it needs, attempt to log you into Steam, and upload the latest version of your game. Steam login is handled by Valve's ~steamcmd~ command line program, not ~dragonruby-publish~. DragonRuby does not ever have access to your login credentials. You may need to take steps to get an authorization token in place if necessary, so you don't have to deal with Steam Guard in automated build processes (documentation on how to do this is forthcoming, or read Valve's SteamCMD manual for details). You (currently) have to set the new build live on the partner site before users will receive it. Optionally automating this step is coming soon! ** Questions/Need Help? You probably have several. Please come visit the Discord and ask questions, and we'll do our best to help, and update this document. S end def docs_dragonruby_philosophy <<-S * DragonRuby's Philosophy The following tenants of DragonRuby are what set us apart from other game engines. Given that Game Toolkit is a relatively new engine, there are definitely features that are missing. So having a big check list of "all the cool things" is not this engine's forte. This is compensated with a strong commitment to the following principles. ** Challenge The Status Quo Game engines of today are in a local maximum and don't take into consideration the challenges of this day and age. Unity and GameMaker specifically rot your brain. It's not sufficient to say: #+begin_quote But that's how we've always done it. #+end_quote It's a hard pill to swallow, but forget blindly accepted best practices and try to figure out the underlying motivation for a specific approach to game development. Collaborate with us. ** Continuity of Design There is a programming idiom in software called "The Pit of Success". The term normalizes upfront pain as a necessity/requirement in the hopes that the investment will yield dividends "when you become successful" or "when the code becomes more complicated". This approach to development is strongly discouraged by us. It leads to over-architected and unnecessary code; creates barriers to rapid prototyping and shipping a game; and overwhelms beginners who are new to the engine or programming in general. DragonRuby's philosophy is to provide multiple options across the "make it fast" vs "make it right" spectrum, with incremental/intuitive transitions between the options provided. A concrete example of this philosophy would be render primitives: the spectrum of options allows renderable constructs that take the form of tuples/arrays (easy to pickup, simple, and fast to code/prototype with), hashes (a little more work, but gives you the ability to add additional properties), open and strict entities (more work than hashes, but yields cleaner apis), and finally - if you really need full power/flexibility in rendering - classes (which take the most amount of code and programming knowledge to create). ** Release Early and Often The biggest mistake game devs make is spending too much time in isolation building their game. Release something, however small, and release it soon. Stop worrying about everything being pixel perfect. Don't wait until your game is 100% complete. Build your game publicly and iterate. Post in the #show-and-tell channel in the community Discord. You'll find a lot of support and encouragement there. Real artists ship. Remember that. ** Sustainable And Ethical Monetization We all aspire to put food on the table doing what we love. Whether it is building games, writing tools to support game development, or anything in between. Charge a fair amount of money for the things you create. It's expected and encouraged within the community. Give what you create away for free to those that can't afford it. If you are gainfully employed, pay full price for the things you use. If you do end up getting something at a discount, pay the difference "forward" to someone else. ** Sustainable And Ethical Open Source This goes hand in hand with sustainable and ethical monetization. The current state of open source is not sustainable. There is an immense amount of contributor burnout. Users of open source expect everything to be free, and few give back. This is a problem we want to fix (we're still trying to figure out the best solution). So, don't be "that guy" in the Discord that says "DragonRuby should be free and open source!" You will be personally flogged by Amir. ** People Over Entities We prioritize the endorsement of real people over faceless entities. This game engine, and other products we create, are not insignificant line items of a large company. And you aren't a generic "commodity" or "corporate resource". So be active in the community Discord and you'll reap the benefits as more devs use DragonRuby. ** Building A Game Should Be Fun And Bring Happiness We will prioritize the removal of pain. The aesthetics of Ruby make it such a joy to work with, and we want to capture that within the engine. ** Real World Application Drives Features We are bombarded by marketing speak day in and day out. We don't do that here. There are things that are really great in the engine, and things that need a lot of work. Collaborate with us so we can help you reach your goals. Ask for features you actually need as opposed to anything speculative. We want DragonRuby to *actually* help you build the game you want to build (as opposed to sell you something piece of demoware that doesn't work). S end def docs_ticks_and_frames <<-S * RECIPIES: ** How To Determine What Frame You Are On There is a property on ~state~ called ~tick_count~ that is incremented by DragonRuby every time the ~tick~ method is called. The following code renders a label that displays the current ~tick_count~. #+begin_src ruby def tick args args.outputs.labels << [10, 670, "\#{args.state.tick_count}"] end #+end_src ** How To Get Current Framerate Current framerate is a top level property on the Game Toolkit Runtime and is accessible via ~args.gtk.current_framerate~. #+begin_src ruby def tick args args.outputs.labels << [10, 710, "framerate: \#{args.gtk.current_framerate.round}"] end #+end_src S end def docs_sprites <<-S ** How To Render A Sprite Using An Array All file paths should use the forward slash ~/~ *not* backslash ~\~. Game Toolkit includes a number of sprites in the ~sprites~ folder (everything about your game is located in the ~mygame~ directory). The following code renders a sprite with a ~width~ and ~height~ of ~100~ in the center of the screen. ~args.outputs.sprites~ is used to render a sprite. #+begin_src ruby def tick args args.outputs.sprites << [ 640 - 50, # X 360 - 50, # Y 100, # W 100, # H 'sprites/square-blue.png' # PATH ] end #+end_src ** More Sprite Properties As An Array Here are all the properties you can set on a sprite. #+begin_src ruby def tick args args.outputs.sprites << [ 100, # X 100, # Y 32, # W 64, # H 'sprites/square-blue.png', # PATH 0, # ANGLE 255, # ALPHA 0, # RED_SATURATION 255, # GREEN_SATURATION 0 # BLUE_SATURATION ] end #+end_src ** Different Sprite Representations Using ordinal positioning can get a little unruly given so many properties you have control over. You can represent a sprite as a ~Hash~: #+begin_src ruby def tick args args.outputs.sprites << { x: 640 - 50, y: 360 - 50, w: 100, h: 100, path: 'sprites/square-blue.png', angle: 0, a: 255, r: 255, g: 255, b: 255, # source_ properties have origin of bottom left source_x: 0, source_y: 0, source_w: -1, source_h: -1, # tile_ properties have origin of top left tile_x: 0, tile_y: 0, tile_w: -1, tile_h: -1, flip_vertically: false, flip_horizontally: false, angle_anchor_x: 0.5, angle_anchor_y: 1.0, blendmode_enum: 1 # labels anchor/alignment (default is nil) # if these values are provided, they will be used over alignment_enum and vertical_alignment_enum anchor_x: 0.5, anchor_y: 0.5 } end #+end_src The ~blendmode_enum~ value can be set to ~0~ (no blending), ~1~ (alpha blending), ~2~ (additive blending), ~3~ (modulo blending), ~4~ (multiply blending). You can represent a sprite as an ~object~: #+begin_src ruby # Create type with ALL sprite properties AND primitive_marker class Sprite attr_accessor :x, :y, :w, :h, :path, :angle, :a, :r, :g, :b, :source_x, :source_y, :source_w, :source_h, :tile_x, :tile_y, :tile_w, :tile_h, :flip_horizontally, :flip_vertically, :angle_anchor_x, :angle_anchor_y, :blendmode_enum, :anchor_x, :anchor_y def primitive_marker :sprite end end class BlueSquare < Sprite def initialize opts @x = opts[:x] @y = opts[:y] @w = opts[:w] @h = opts[:h] @path = 'sprites/square-blue.png' end end def tick args args.outputs.sprites << (BlueSquare.new x: 640 - 50, y: 360 - 50, w: 50, h: 50) end #+end_src S end def docs_labels <<-S ** How To Render A Label ~args.outputs.labels~ is used to render labels. Labels are how you display text. This code will go directly inside of the ~def tick args~ method. Here is the minimum code: #+begin_src def tick args # X Y TEXT args.outputs.labels << [640, 360, "I am a black label."] end #+end_src ** A Colored Label #+begin_src def tick args # A colored label # X Y TEXT, RED GREEN BLUE ALPHA args.outputs.labels << [640, 360, "I am a redish label.", 255, 128, 128, 255] end #+end_src ** Extended Label Properties #+begin_src def tick args # A colored label # X Y TEXT SIZE ALIGNMENT RED GREEN BLUE ALPHA FONT FILE args.outputs.labels << [ 640, # X 360, # Y "Hello world", # TEXT 0, # SIZE_ENUM 1, # ALIGNMENT_ENUM 0, # RED 0, # GREEN 0, # BLUE 255, # ALPHA "fonts/coolfont.ttf" # FONT ] end #+end_src A ~SIZE_ENUM~ of ~0~ represents "default size". A ~negative~ value will decrease the label size. A ~positive~ value will increase the label's size. An ~ALIGNMENT_ENUM~ of ~0~ represents "left aligned". ~1~ represents "center aligned". ~2~ represents "right aligned". ** Rendering A Label As A ~Hash~ You can add additional metadata about your game within a label, which requires you to use a `Hash` instead. If you use a ~Hash~ to render a label, you can set the label's size using either ~SIZE_ENUM~ or ~SIZE_PX~. If both options are provided, ~SIZE_PX~ will be used. #+begin_src def tick args args.outputs.labels << { x: 200, y: 550, text: "dragonruby", # size specification can be either size_enum or size_px size_enum: 2, size_px: 22, alignment_enum: 1, r: 155, g: 50, b: 50, a: 255, font: "fonts/manaspc.ttf", vertical_alignment_enum: 0, # 0 is bottom, 1 is middle, 2 is top anchor_x: 0.5, anchor_y: 0.5 # You can add any properties you like (this will be ignored/won't cause errors) game_data_one: "Something", game_data_two: { value_1: "value", value_2: "value two", a_number: 15 } } end #+end_src ** Getting The Size Of A Piece Of Text You can get the render size of any string using ~args.gtk.calcstringbox~. #+begin_src ruby def tick args # TEXT SIZE_ENUM FONT w, h = args.gtk.calcstringbox("some string", 0, "font.ttf") # NOTE: The SIZE_ENUM and FONT are optional arguments. # Render a label showing the w and h of the text: args.outputs.labels << [ 10, 710, # This string uses Ruby's string interpolation literal: \#{} "'some string' has width: \#{w}, and height: \#{h}." ] end #+end_src ** Rendering Labels With New Line Characters And Wrapping You can use a strategy like the following to create multiple labels from a String. #+begin_src ruby def tick args long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elitteger dolor velit, ultricies vitae libero vel, aliquam imperdiet enim." max_character_length = 30 long_strings_split = args.string.wrapped_lines long_string, max_character_length args.outputs.labels << long_strings_split.map_with_index do |s, i| { x: 10, y: 600 - (i * 20), text: s } end end #+end_src S end def docs_sounds <<-S ** How To Play A Sound Sounds that end ~.wav~ will play once: #+begin_src ruby def tick args # Play a sound every second if (args.state.tick_count % 60) == 0 args.outputs.sounds << 'something.wav' end end #+end_src Sounds that end ~.ogg~ is considered background music and will loop: #+begin_src ruby def tick args # Start a sound loop at the beginning of the game if args.state.tick_count == 0 args.outputs.sounds << 'background_music.ogg' end end #+end_src If you want to play a ~.ogg~ once as if it were a sound effect, you can do: #+begin_src ruby def tick args # Play a sound every second if (args.state.tick_count % 60) == 0 args.gtk.queue_sound 'some-ogg.ogg' end end #+end_src S end def docs_game_state <<-S ** Using ~args.state~ To Store Your Game State ~args.state~ is a open data structure that allows you to define properties that are arbitrarily nested. You don't need to define any kind of ~class~. To initialize your game state, use the ~||=~ operator. Any value on the right side of ~||=~ will only be assigned _once_. To assign a value every frame, just use the ~=~ operator, but _make sure_ you've initialized a default value. #+begin_src def tick args # initialize your game state ONCE args.state.player.x ||= 0 args.state.player.y ||= 0 args.state.player.hp ||= 100 # increment the x position of the character by one every frame args.state.player.x += 1 # Render a sprite with a label above the sprite args.outputs.sprites << [ args.state.player.x, args.state.player.y, 32, 32, "player.png" ] args.outputs.labels << [ args.state.player.x, args.state.player.y - 50, args.state.player.hp ] end #+end_src S end def docs_accessing_files <<-S ** Accessing files DragonRuby uses a sandboxed filesystem which will automatically read from and write to a location appropriate for your platform so you don't have to worry about theses details in your code. You can just use ~gtk.read_file~, ~gtk.write_file~, and ~gtk.append_file~ with a relative path and the engine will take care of the rest. The data directories that will be written to in a production build are: - Windows: ~C:\\Users\\[username]\\AppData\\Roaming\\[devtitle]\\[gametitle]~ - MacOS: ~$HOME/Library/Application Support/[gametitle]~ - Linux: ~$HOME/.local/share/[gametitle]~ - HTML5: The data will be written to the browser's IndexedDB. The values in square brackets are the values you set in your ~app/metadata/game_metadata.txt~ file. When reading files, the engine will first look in the game's data directory and then in the game directory itself. This means that if you write a file to the data directory that already exists in your game directory, the file in the data directory will be used instead of the one that is in your game. When running a development build you will directly write to your game directory (and thus overwrite existing files). This can be useful for built-in development tools like level editors. For more details on the implementation of the sandboxed filesystem, see Ryan C. Gordon's PhysicsFS documentation: [[https://icculus.org/physfs/]] S end def animate_a_sprite <<-S ** How To Animate A Sprite Using Separate PNGs DragonRuby has a property on ~Numeric~ called ~frame_index~ that can be used to determine what frame of an animation to show. Here is an example of how to cycle through 6 sprites every 4 frames. #+begin_src ruby def tick args start_looping_at = 0 number_of_sprites = 6 number_of_frames_to_show_each_sprite = 4 does_sprite_loop = true sprite_index = start_looping_at.frame_index number_of_sprites, number_of_frames_to_show_each_sprite, does_sprite_loop sprite_index ||= 0 args.outputs.sprites << [ 640 - 50, 360 - 50, 100, 100, "sprites/dragon-\#{sprite_index}.png" ] end #+end_src S end def docs_troubleshooting_performance <<-S ** Troubleshoot Performance 1. If you're using ~Array~s for your primitives (~args.outputs.sprites << []~), use ~Hash~ instead (~args.outputs.sprites << { x: ... }~). 2. If you're using ~Entity~ for your primitives (~args.outputs.sprites << args.state.new_entity~), use ~StrictEntity~ instead (~args.outputs.sprites << args.state.new_entity_strict~). 3. Use ~.each~ instead of ~.map~ if you don't care about the return value. 4. When concatenating primitives to outputs, do them in bulk. Instead of: #+begin_src ruby args.state.bullets.each do |bullet| args.outputs.sprites << bullet.sprite end #+end_src do #+begin_src args.outputs.sprites << args.state.bullets.map do |b| b.sprite end #+end_src 5. Use ~args.outputs.static_~ variant for things that don't change often (take a look at the Basic Gorillas sample app and Dueling Starships sample app to see how ~static_~ is leveraged. 6. Consider using a ~render_target~ if you're doing some form of a camera that moves a lot of primitives (take a look at the Render Target sample apps for more info). S end def scale_sprites <<-S ** How to Scale a Sprite The ~scale_rect~ method can be used to change the scale of a sprite by a given ~ratio~. Optionally, you can scale the sprite around a specified anchor point. In the example below, setting both ~anchor_x~ and ~anchor_y~ to 0.5 scales the sprite proportionally on all four sides). See also: ~Geometry#scale_rect~ #+begin_src ruby def tick args # x, y, w, h, path my_sprite = [590, 310, 100, 100, 'sprites/circle.png'] # scale a sprite with a ratio of 2 (double the size) # and anchor the transformation around the center of the sprite # ratio, anchor_x, anchor_y my_scaled_sprite = my_sprite.scale_rect(2, 0.5, 0.5) args.outputs.sprites << [my_scaled_sprite, "sprites/circle.png"] end #+end_src S end def docs_faq <<-S * Frequently Asked Questions, Comments, and Concerns Here are questions, comments, and concerns that frequently come up. ** Frequently Asked Questions *** What is DragonRuby LLP? DragonRuby LLP is a partnership of four devs who came together with the goal of bringing the aesthetics and joy of Ruby, everywhere possible. Under DragonRuby LLP, we offer a number of products (with more on the way): - Game Toolkit (GTK): A 2D game engine that is compatible with modern gaming platforms. - RubyMotion (RM): A compiler toolchain that allows you to build native, cross-platform mobile apps. [[http://rubymotion.com]] All of the products above leverage a shared core called DragonRuby. NOTE: From an official branding standpoint each one of the products is suffixed with "A DragonRuby LLP Product" tagline. Also, DragonRuby is _one word, title cased_. NOTE: We leave the "A DragonRuby LLP Product" off of this one because that just sounds really weird. NOTE: Devs who use DragonRuby are "Dragon Riders/Riders of Dragons". That's a bad ass identifier huh? *** What is DragonRuby? The response to this question requires a few subparts. First we need to clarify some terms. Specifically _language specification_ vs _runtime_. **** Okay... so what is the difference between a language specification and a runtime? A runtime is an _implementation_ of a language specification. When people say "Ruby," they are usually referring to "the Ruby 3.0+ language specification implemented via the CRuby/MRI Runtime." But, there are many Ruby Runtimes: CRuby/MRI, JRuby, Truffle, Rubinius, Artichoke, and (last but certainly not least) DragonRuby. **** Okay... what language specification does DragonRuby use then? DragonRuby's goal is to be compliant with the ISO/IEC 30170:2012 standard. It's syntax is Ruby 2.x compatible, but also contains semantic changes that help it natively interface with platform specific libraries. **** So... why another runtime? The elevator pitch is: DragonRuby is a Multilevel Cross-platform Runtime. The "multiple levels" within the runtime allows us to target platforms no other Ruby can target: PC, Mac, Linux, Raspberry Pi, WASM, iOS, Android, Nintendo Switch, PS4, Xbox, and Stadia. **** What does Multilevel Cross-platform mean? There are complexities associated with targeting all the platforms we support. Because of this, the runtime had to be architected in such a way that new platforms could be easily added (which lead to us partitioning the runtime internally): - Level 1 we leverage a good portion of mRuby. - Level 2 consists of optimizations to mRuby we've made given that our target platforms are well known. - Level 3 consists of portable C libraries and their Ruby C-Extensions. Levels 1 through 3 are fairly commonplace in many runtime implementations (with level 1 being the most portable, and level 3 being the fastest). But the DragonRuby Runtime has taken things a bit further: - Level 4 consists of shared abstractions around hardware I/O and operating system resources. This level leverages open source and proprietary components within Simple DirectMedia Layer (a low level multimedia component library that has been in active development for 22 years and counting). - Level 5 is a code generation layer which creates metadata that allows for native interoperability with host runtime libraries. It also includes OS specific message pump orchestrations. - Level 6 is a Ahead of Time/Just in Time Ruby compiler built with LLVM. This compiler outputs _very_ fast platform specific bitcode, but only supports a subset of the Ruby language specification. These levels allow us to stay up to date with open source implementations of Ruby; provide fast, native code execution on proprietary platforms; ensure good separation between these two worlds; and provides a means to add new platforms without going insane. **** Cool cool. So given that I understand everything to this point, can we answer the original question? What is DragonRuby? DragonRuby is a Ruby runtime implementation that takes all the lessons we've learned from MRI/CRuby, and merges it with the latest and greatest compiler and OSS technologies. *** How is DragonRuby different than MRI? DragonRuby supports a subset of MRI apis. Our target is to support all of mRuby's standard lib. There are challenges to this given the number of platforms we are trying to support (specifically console). **** Does DragonRuby support Gems? DragonRuby does not support gems because that requires the installation of MRI Ruby on the developer's machine (which is a non-starter given that we want DragonRuby to be a zero dependency runtime). While this seems easy for Mac and Linux, it is much harder on Windows and Raspberry Pi. mRuby has taken the approach of having a git repository for compatible gems and we will most likely follow suite: [[https://github.com/mruby/mgem-list]]. **** Does DragonRuby have a REPL/IRB? You can use DragonRuby's Console within the game to inspect object and execute small pieces of code. For more complex pieces of code create a file called ~repl.rb~ and put it in ~mygame/app/repl.rb~: - Any code you write in there will be executed when you change the file. You can organize different pieces of code using the ~repl~ method: #+begin_src ruby repl do puts "hello world" puts 1 + 1 end #+end_src - If you use the `repl` method, the code will be executed and the DragonRuby Console will automatically open so you can see the results (on Mac and Linux, the results will also be printed to the terminal). - All ~puts~ statements will also be saved to ~logs/puts.txt~. So if you want to stay in your editor and not look at the terminal, or the DragonRuby Console, you can ~tail~ this file. 4. To ignore code in ~repl.rb~, instead of commenting it out, prefix ~repl~ with the letter ~x~ and it'll be ignored. #+begin_src ruby xrepl do # <------- line is prefixed with an "x" puts "hello world" puts 1 + 1 end # This code will be executed when you save the file. repl do puts "Hello" end repl do puts "This code will also be executed." end # use xrepl to "comment out" code xrepl do puts "This code will not be executed because of the x in front of repl". end #+end_src **** Does DragonRuby support ~pry~ or have any other debugging facilities? ~pry~ is a gem that assumes you are using the MRI Runtime (which is incompatible with DragonRuby). Eventually DragonRuby will have a pry based experience that is compatible with a debugging infrastructure called LLDB. Take the time to read about LLDB as it shows the challenges in creating something that is compatible. You can use DragonRuby's replay capabilities to troubleshoot: 1. DragonRuby is hot loaded which gives you a very fast feedback loop (if the game throws an exception, it's because of the code you just added). 2. Use ~./dragonruby mygame --record~ to create a game play recording that you can use to find the exception (you can replay a recording by executing ~./dragonruby mygame --replay last_replay.txt~ or through the DragonRuby Console using ~$gtk.recording.start_replay "last_replay.txt"~. 3. DragonRuby also ships with a unit testing facility. You can invoke the following command to run a test: ~./dragonruby mygame --test tests/some_ruby_file.rb~. 4. Get into the habit of adding debugging facilities within the game itself. You can add drawing primitives to ~args.outputs.debug~ that will render on top of your game but will be ignored in a production release. 5. Debugging something that runs at 60fps is (imo) not that helpful. The exception you are seeing could have been because of a change that occurred many frames ago. ** Frequent Comments About Ruby as a Language Choice *** But Ruby is dead. Let's check the official source for the answer to this question: isrubydead.com: [[https://isrubydead.com/]]. On a more serious note, Ruby's _quantity_ levels aren't what they used to be. And that's totally fine. Everyone chases the new and shiny. What really matters is _quality/maturity_. Here's a StackOverflow Survey sorted by highest paid developers: [[https://insights.stackoverflow.com/survey/2021#section-top-paying-technologies-top-paying-technologies]]. Let's stop making this comment shall we? *** But Ruby is slow. That doesn't make any sense. A language specification can't be slow... it's a language spec. Sure, an _implementation/runtime_ can be slow though, but then we'd have to talk about which runtime. Here's a some quick demonstrations of how well DragonRuby Game Toolkit Performs: - DragonRuby vs Unity: [[https://youtu.be/MFR-dvsllA4]] - DragonRuby vs PyGame: [[https://youtu.be/fuRGs6j6fPQ]] *** Dynamic languages are slow. They are certainly slower than statically compiled languages. With the processing power and compiler optimizations we have today, dynamic languages like Ruby are _fast enough_. Unless you are writing in some form of intermediate representation by hand, your language of choice also suffers this same fallacy of slow. Like, nothing is faster than a low level assembly-like language. So unless you're writing in that, let's stop making this comment. NOTE: If you _are_ hand writing LLVM IR, we are always open to bringing on new partners with such a skill set. Email us ^_^. ** Frequent Concerns *** DragonRuby is not open source. That's not right. The current state of open source is unsustainable. Contributors work for free, most all open source repositories are severely under-staffed, and burnout from core members is rampant. We believe in open source very strongly. Parts of DragonRuby are in fact, open source. Just not all of it (for legal reasons, and because the IP we've created has value). And we promise that we are looking for (or creating) ways to _sustainably_ open source everything we do. If you have ideas on how we can do this, email us! If the reason above isn't sufficient, then definitely use something else. All this being said, we do have parts of the engine open sourced on GitHub: [[https://github.com/dragonruby/dragonruby-game-toolkit-contrib/]] *** DragonRuby is for pay. You should offer a free version. If you can afford to pay for DragonRuby, you should (and will). We don't tell authors that they should give us their books for free, and only require payment if we read the entire thing. It's time we stop asking that of software products. That being said, we will _never_ put someone out financially. We have income assistance for anyone that can't afford a license to any one of our products. You qualify for a free, unrestricted license to DragonRuby products if any of the following items pertain to you: - Your income is below $2,000.00 (USD) per month. - You are under 18 years of age. - You are a student of any type: traditional public school, home schooling, college, bootcamp, or online. - You are a teacher, mentor, or parent who wants to teach a kid how to code. - You work/worked in public service or at a charitable organization: for example public office, army, or any 501(c)(3) organization. Just contact Amir at amir.rajan@dragonruby.org with a short explanation of your current situation and he'll set you up. No questions asked. *** But still, you should offer a free version. So I can try it out and see if I like it. You can try our web-based sandbox environment at [[http://fiddle.dragonruby.org]]. But it won't do the runtime justice. Or just come to our Discord Channel at [[http://discord.dragonruby.org]] and ask questions. We'd be happy to have a one on one video chat with you and show off all the cool stuff we're doing. Seriously just buy it. Get a refund if you don't like it. We make it stupid easy to do so. *** I still think you should do a free version. Think of all people who would give it a shot. Free isn't a sustainable financial model. We don't want to spam your email. We don't want to collect usage data off of you either. We just want to provide quality toolchains to quality developers (as opposed to a large quantity of developers). The people that pay for DragonRuby and make an effort to understand it are the ones we want to build a community around, partner with, and collaborate with. So having that small monetary wall deters entitled individuals that don't value the same things we do. *** What if I build something with DragonRuby, but DragonRuby LLP becomes insolvent. We want to be able to work on the stuff we love, every day of our lives. And we'll go to great lengths to make that continues. But, in the event that sad day comes, our partnership bylaws state that _all_ DragonRuby IP that can be legally open sourced, will be released under a permissive license. S end end class ReadMe extend Docs extend ReadMeDocs end end
true
2ca5b764134e35e14562d55ba81acbe5bf70893d
Ruby
jinascimento/task_manager
/app/services/tasks/task_creator.rb
UTF-8
418
2.59375
3
[]
no_license
class Tasks::TaskCreator COLOR_BY_PRIORITY = { low: '#6fd86f', medium: '#7471F9', high: '#FF2A2B' }.freeze def initialize(params) @params = params end def call @task = Task.new(@params) @task.pending! set_color_by_priority OpenStruct.new(success?: @task.save, task: @task, errors: nil) end def set_color_by_priority @task.color = COLOR_BY_PRIORITY[@task.priority.to_sym] end end
true
deeeccd902643d7d9efdb353bd3573dc239d0f5f
Ruby
edwinlin/cartoon-collections-dumbo-web-career-010719
/cartoon_collections.rb
UTF-8
436
3.140625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves(dwarves) dwarves.each_with_index {|dwarf, idx| puts "#{idx+1} #{dwarf}"} end def summon_captain_planet(array) return array.map {|ele| ele[0].upcase + ele[1...ele.length] + "!"} end def long_planeteer_calls(array) return array.any? {|ele| ele.length > 4} end def find_the_cheese(snacks) cheese_types = ["cheddar", "gouda", "camembert"] snacks.find do |snack| cheese_types.include?(snack) end end
true
32390b645a48d0a44a11ae048eda87f7c5b44157
Ruby
willpiers/tic-tac-toe
/lib/ttt_io.rb
UTF-8
2,046
3.828125
4
[]
no_license
class TttIO def self.determine_opponent_type puts "would you like to play against a friend, or the computer?" answer = nil until ['1','2'].include? answer puts "press 1 for computer, and 2 for human." answer = accept_input end answer == '1' ? :computer : :human end def self.determine_first_player puts "who should go first?" answer = nil until ['1','2'].include? answer puts "press 1 for you, and 2 for the other player." answer = accept_input end answer == '1' ? :user : :other end def self.determine_user_move board, mark puts "Pick an open square to move." puts "You're #{mark}'s, in case you forgot." loop do raw_location = accept_input.to_i if board.available?(raw_location) mark_location = Board.to_coordinates(raw_location) return mark_location else puts "Please choose an available space on the board." end end end def self.draw board colors = color_board(board) clear_screen puts " | | " puts " #{ colors[0] } | #{ colors[1] } | #{ colors[2] }" puts "_____|_____|_____" puts " | | " puts " #{ colors[3] } | #{ colors[4] } | #{ colors[5] }" puts "_____|_____|_____" puts " | | " puts " #{ colors[6] } | #{ colors[7] } | #{ colors[8] }" puts " | | " end def self.clear_screen; system 'clear'; end def self.color_board board board.cells.flatten.map do |entry| case entry when board.x_marker then entry.colorize(:blue) when board.o_marker then entry.colorize(:red) else entry end end end def self.congratulate_winner game winner = game.board.x_marker if game.board.check_all_lines(game.board.x_marker) winner = game.board.o_marker if game.board.check_all_lines(game.board.o_marker) message = winner ? "Good job #{winner}'s" : "Cat's game!" puts message end private def self.accept_input gets.chomp end end
true
b52ba0a4c834ccb72376108b7d8e4e0f5b7daffd
Ruby
substantial/sous-chef
/lib/sous-chef/node_manager.rb
UTF-8
372
2.53125
3
[ "MIT" ]
permissive
class SousChef::NodeManager attr_reader :parser, :nodes def initialize(config_file) @parser = SousChef::Parser.new(config_file) @nodes = {} initialize_node_collections end private def initialize_node_collections @parser.parse.each do |name, collection| @nodes[name] = SousChef::NodeBuilder.new(name, collection).build end end end
true
d8bf236d675939fc2f1c2cb548beb83187d207c0
Ruby
ID25/caesar
/test/services/cipher_test.rb
UTF-8
490
2.796875
3
[]
no_license
require 'test_helper' class CipherTest < ActiveSupport::TestCase test 'correct decrypted text' do shift = 3 text = 'hello world' cipher = Cipher.new(text, shift) encrypted_text = 'khoor zruog' assert cipher.encrypt(text), encrypted_text end test 'correct encrypted text in other lang' do shift = 9 text = 'привет мир' cipher = Cipher.new(text, shift) encrypted_text = 'чшркнъ фрш' assert cipher.decrypt(encrypted_text), text end end
true
4c7203d9f3ee2d44072e808c2f335a9422b922de
Ruby
RossKinsella/CS4032-lab-1
/lab-1.rb
UTF-8
496
3.390625
3
[]
no_license
require 'socket' class String def string_between_markers marker1, marker2 self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1] end end message = "hello" socket = TCPSocket.new 'localhost', 8000 socket.puts "GET /distributed-sytems-lab-1.php?message=#{message} HTTP/1.0\r\n\r\n" response = socket.recv(1000) capitalised_message = response.string_between_markers "\r\n\r\n", "\\n" puts "The server recieved our message '#{message}' and returned '#{capitalised_message}'"
true
2d150156a8ca07c424d5d61540a7ad8caf06a07e
Ruby
rcjara/git-writing-tool
/lib/git_writing_tool.rb
UTF-8
771
2.6875
3
[]
no_license
require_relative 'file_reader.rb' require_relative 'section.rb' require_relative 'section_displayer.rb' require_relative 'composer.rb' module GWT def self.run_file(filename) full_filename = (filename =~ /\./) ? filename : filename + '.rb' GWT::Runner.new(full_filename).instance_eval(File.read(full_filename)) end class Runner def initialize(filename = nil) @filename = filename end def compose(filename = nil, &block) filename ||= @filename composer = GWT::Composer.new(filename, &block) File.open(composer.filename, 'w') do |f| f << composer.formatted_text end end def get_calling_file full_file_path = caller[0].sub(/:.*?$/, '') File.basename(full_file_path) end end end
true
49b2c65c7f06db80adfa9d64d035135ee769213d
Ruby
bsanyi/erlang-etf
/lib/erlang/etf/extensions/symbol.rb
UTF-8
844
2.671875
3
[ "MIT" ]
permissive
module Erlang module ETF module Extensions module Symbol def __erlang_type__ if to_s.bytesize < 256 if to_s.ascii_only? :small_atom else :small_atom_utf8 end else if to_s.ascii_only? :atom else :atom_utf8 end end end def __erlang_evolve__ case __erlang_type__ when :atom ETF::Atom.new(to_s) when :atom_utf8 ETF::AtomUTF8.new(to_s) when :small_atom ETF::SmallAtom.new(to_s) when :small_atom_utf8 ETF::SmallAtomUTF8.new(to_s) end end def to_utf8_binary to_s.to_utf8_binary end end end end end
true
a70a240f982c903aeb605b140afca37289725652
Ruby
marcripley/BioshockTA
/lib/rapturesubs.rb
UTF-8
1,633
3.6875
4
[]
no_license
# Initializes the player and stores the name, current location, health and inventory class Player attr_accessor :name, :difficulty, :location, :health, :weapons, :inventory def initialize(player_name, difficulty) @name = player_name @difficulty = difficulty @health = 100 @weapons = [] @inventory = [] end def list_inventory "You have a " + (@weapons + @inventory).join(', ') end end # This class defines the rooms in Rapture with their connections, items, and enemies # Bonus items (with random odds) could be included later to include bandages, food, etc... class Room attr_accessor :reference, :name, :description, :connections, :items, :enemies def initialize(reference, name, description, connections, items, enemies) @reference = reference @name = name @description = description @connections = connections @items = items @enemies = enemies # Probability of enemies in room, 0-10 end def full_description "You are in the " + @name + "\n" + @description end # List items in current room, formatted for easy reading def list_items joiner = @items.size > 1 ? ' and ' : ' ' items_message = @items.size == 0 ? "This room is empty." : "You see a " + @items.join(joiner).gsub('_', ' ') + "." return items_message end end class Enemy attr_accessor :name, :health, :power, :strong, :weak def initialize(name, health, power, strong, weak) @name = name @health = health @power = power @strong = strong @weak = weak end end
true
1e9b48396e5c970f80eb39f91c5bedb9cca35e17
Ruby
lmeriluoto/cs61aPrepCourse
/ch8/buildingAndSorting.rb
UTF-8
147
3.484375
3
[]
no_license
puts 'Type as many words as you want!' input = gets.chomp words = [] while input != '' words.push input input = gets.chomp end puts words.sort
true
276f6250b6f431c4ec02d919e20c490cf9c03e26
Ruby
dvdalilue/f_heap
/test/f_heap_test.rb
UTF-8
4,332
3.09375
3
[ "MIT" ]
permissive
require "test_helper" class FHeapTest < ActiveSupport::TestCase def setup @heap = FHeap.new end def setup_sample_heap @node_1 = @heap.insert!(1) @node_2 = @heap.insert!(2) @node_6 = @heap.insert!(6) @node_5 = @node_2.add_child!(5) @node_3 = @node_1.add_child!(3) @node_4 = @node_1.add_child!(4) @node_7 = @node_1.add_child!(7) @node_8 = @node_7.add_child!(8) @node_9 = @node_8.add_child!(9) assert_equal 3, @heap.trees.length assert_equal 1, @heap.min_node.value end test "min_node with no trees" do assert_nil @heap.min_node end test "insert updates min_node" do @heap.insert!(1) assert_equal 1, @heap.min_node.value @heap.insert!(2) assert_equal 1, @heap.min_node.value @heap.insert!(0) assert_equal 0, @heap.min_node.value end test "extract minimum (nothing in the heap)" do assert_nil @heap.extract_minimum! end test "extract minimum (one item in heap)" do @heap.insert!(1) assert_equal 1, @heap.extract_minimum!.value end test "extract minimum (calling after extracting the last node)" do @heap.insert!(1) assert_equal 1, @heap.extract_minimum!.value assert_nil @heap.extract_minimum! end test "extract minimum (restructures correctly)" do setup_sample_heap assert_equal 1, @heap.extract_minimum!.value assert_equal 2, @heap.min_node.value assert_equal ["(2 (5), (3 (6)))", "(4)", "(7 (8 (9)))"], @heap.to_s assert @node_2.root? assert @node_4.root? assert @node_7.root? assert_equal @node_2, @node_5.root assert_equal @node_2, @node_3.root assert_equal @node_2, @node_6.root assert_equal @node_7, @node_8.root assert_equal @node_7, @node_9.root assert_equal @node_2, @node_2.parent assert_equal @node_4, @node_4.parent assert_equal @node_7, @node_7.parent assert_equal @node_2, @node_5.parent assert_equal @node_2, @node_3.parent assert_equal @node_3, @node_6.parent assert_equal @node_7, @node_8.parent assert_equal @node_8, @node_9.parent end test "decrease value (can't set higher than the existing value)" do setup_sample_heap assert_raises ArgumentError do @heap.decrease_value!(@node_9, 100) end end test "decrease value (doesn't do anything if you don't change the value)" do setup_sample_heap structure = @heap.to_s @heap.decrease_value!(@node_9, @node_9.value) assert_equal structure, @heap.to_s end test "decrease value (restructures correctly)" do setup_sample_heap @node_4.marked = true @node_7.marked = true @node_8.marked = true @heap.decrease_value!(@node_0 = @node_9, 0) assert_equal 0, @heap.min_node.value assert_equal ["(1 (3), (4))", "(2 (5))", "(6)", "(0)", "(8)", "(7)"], @heap.to_s assert ((0..8).to_a - [4]).all? { |number| !instance_variable_get(:"@node_#{number}").marked } assert @node_4.marked assert @node_1.root? assert @node_2.root? assert @node_6.root? assert @node_0.root? assert @node_8.root? assert @node_7.root? assert_equal @node_1, @node_3.root assert_equal @node_1, @node_4.root assert_equal @node_2, @node_5.root assert_equal @node_1, @node_3.parent assert_equal @node_1, @node_4.parent assert_equal @node_2, @node_5.parent end test "delete" do setup_sample_heap assert_equal @node_9, @heap.delete(@node_9) assert_equal 1, @heap.min_node.value assert_equal ["(1 (3), (4), (7 (8)))", "(2 (5))", "(6)"], @heap.to_s assert ((1..9).to_a - [8]).all? { |number| !instance_variable_get(:"@node_#{number}").marked } assert @node_8.marked assert @node_1.root? assert @node_2.root? assert @node_6.root? assert_equal @node_1, @node_3.root assert_equal @node_1, @node_4.root assert_equal @node_1, @node_7.root assert_equal @node_1, @node_8.root assert_equal @node_2, @node_5.root assert_equal @node_1, @node_3.parent assert_equal @node_1, @node_4.parent assert_equal @node_1, @node_7.parent assert_equal @node_7, @node_8.parent assert_equal @node_2, @node_5.parent end end
true
84b55cf28598ff79f6c7721e776f10dcedadb609
Ruby
NicholasJYee/mediliza
/app/models/preference.rb
UTF-8
476
2.5625
3
[]
no_license
# Preference record of all the patients # # @attribute patient_id # @return [Integer] id of the patient being interacted with # @attribute description # @return [String] information about the preference # @attribute likes # @return [Boolean] true for likes and false for dislikes class Preference < ActiveRecord::Base # Gives back the patient involved in the interaction # # @return [Patient] gives the patient involved in the interaction belongs_to :patient end
true
308aa64ba1748dfa85f0e144b88460b02522ebf7
Ruby
jdbernardi/assignment_oop_warmups_1
/fib.rb
UTF-8
558
4.15625
4
[]
no_license
## FIBONACCI SEQUENCE ## def fibs( num ) # initial array for fibonacci fib_start = [0,1] index = 0 if num == 1 print [0] return [0] end # until the count of result is the given num until fib_start.count >= num # if the array is 1 or 2 we return [0] or [0,1] fib_start << fib_start[ index ] + fib_start[ index + 1 ] # we add index 0 and index 1 and push into the array # we then increment to the next index and continue to push index += 1 end print fib_start end puts "\rEnter a number\r" num = gets.strip fibs(num.to_i)
true
06851a7fea398c867cbb55e1ed7727a74e988d77
Ruby
pgaret/ttt-with-ai-project-web-0916
/lib/board.rb
UTF-8
888
3.84375
4
[]
no_license
require 'pry' class Board attr_accessor :cells def initialize @cells = [" ", " ", " ", " ", " ", " ", " ", " ", " "] end def reset! @cells = [" ", " ", " ", " ", " ", " ", " ", " ", " "] end def display print "\n-----------\n" for i in 0..8 if i % 3 == 0 || i % 3 == 2 then print " #{cells[i]} " elsif i % 3 == 1 then print "| #{cells[i]} |" end if i % 3 == 2 then print "\n-----------\n" end end end def update(position, player) @cells[position.to_i - 1] = player.token end def position(input) @cells[input.to_i - 1] end def full? !cells.include?(" ") end def turn_count @cells.select{|cell| cell != " "}.count end def taken?(space) position(space) != " " end def valid_move?(space) if space.to_i > 0 && space.to_i < 10 && !taken?(space) then true else false end end end
true
10ca1be7c663c541418c960edc6d2366e203ce9c
Ruby
bchandramouli/ruby_test_progs
/cookbook.rb
UTF-8
993
3.828125
4
[]
no_license
#!/usr/bin/env ruby class Cookbook attr_accessor :title attr_reader :recipes def initialize(title) @title = title @recipes = [] end def add_recipes(recipe) @recipes << recipe p "Added a recipe #{recipe.title} to the collection #{@title}" end def recipe_titles() @recipes.each { |r| p r.title } end def recipe_ingredients() @recipes.each { |r| p r.ingredients } end def print_cookbook() @recipes.each {|r| r.print_recipe } end end class Recipe attr_accessor :title, :ingredients, :steps def initialize(title, ingredients, steps) @title = title @ingredients = ingredients @steps = steps end def add_ingredients(ingr) @ingredients.push(ingr) end def add_steps(num, step) @steps.insert(num, step) end def print_recipe puts "Recipe: #{@title}" puts "Ingredients: #{@ingredients.join(' ')}" s_str = "" @steps.each do |s| s_str << (@steps.index(s) + 1).to_s + ". " + s + "\n" end puts "Steps: \n#{s_str}" puts "\n" end end
true
dbb86eb008b19a988c6fea5f0a1e47038b52ee9d
Ruby
mliq/ruby
/StoS.rb
UTF-8
211
3.015625
3
[]
no_license
h = {"dog"=>"puppy", "cat"=>"kitty", "goat"=>"kitty"} g = {} h.each do |key,value| # puts "#{key} #{value}" # h.delete[key] key=key.gsub(/\s+/,"_").downcase.to_sym g[key] = value end puts h puts g
true
d61fc243aa479642ba14dc98449199d76ce95b3d
Ruby
yamashita-tomonori/object_brain
/ob_4_6/bucho.rb
UTF-8
200
2.765625
3
[]
no_license
# coding: utf-8 require './shain.rb' class Bucho < Shain def initialize(name, kihonkyu) super(name, kihonkyu) end def yakushoku '部長' end def kyuryo @kihonkyu * 3 end end
true
30e68a4b89cb399c2d6d712e97900f732e7042b0
Ruby
kanamikiii/final
/lib/tasks/sample_data.rake
UTF-8
2,427
2.625
3
[]
no_license
namespace :db do desc "Fill database with sample data" task populate: :environment do make_users make_entries make_comments make_relationships # admin = User.create!(name: "Example User", # email: "admin@admin.com", # password: "admin12345", # password_confirmation: "admin12345", # admin: true) # 99.times do |n| # name = Faker::Name.name # email = "example-#{n+1}@railstutorial.org" # password = "password" # User.create!(name: name, # email: email, # password: password, # password_confirmation: password) # end # users = User.limit(6).all # 50.times do # content = Faker::Lorem.sentence(5) # users.each { |user| user.microposts.create!(content: content) } # end # users = User.all # user = users.first # followed_users = users[2..50] # followers = users[3..40] # followed_users.each { |followed| user.follow!(followed) } # followers.each { |follower| follower.follow!(user) } end end def make_users admin = User.create!(name: "Admin", email: "admin@admin.com", password: "admin12345", password_confirmation: "admin12345", admin: true) 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(name: name, email: email, password: password, password_confirmation: password) end end def make_entries users = User.limit(6).all 20.times do title = Faker::Lorem.words(5).join(" ") #body = Faker::Lorem.paragraphs(2).join(" ") body = Faker::Lorem.sentence(5) users.each do |user| user.entries.create!(title: title, body: body) end end end def make_comments users = User.limit(3).all users.each do |user| 2.times do content = Faker::Lorem.words(10).join(" ") user.entries.each do |entry| 2.times do entry.comments.create!(content: content) end end end end end def make_relationships users = User.all user = users.first followed_users = users[2..50] followers = users[3..40] followed_users.each { |followed| user.follow!(followed) } followers.each { |follower| follower.follow!(user) } end
true
5c92066b435ecf70e5469607a3cd5e13cd4707fc
Ruby
nkansal96/aurora-ruby
/bin/aurora-tts
UTF-8
760
2.71875
3
[]
no_license
#!/usr/bin/env ruby require 'aurora-sdk' if ARGV.length == 4 text = ARGV[0] filename = ARGV[1].dup app_id = ARGV[2] app_token = ARGV[3] if !filename.downcase.end_with? '.wav' filename << '.wav' end begin Aurora.config = Aurora::Config.new(app_id, app_token) res = Aurora::Api.get_tts(text) rescue StandardError => e puts e.message exit end begin open(filename, 'wb') do |file| file.write(res.audio.to_wav) end rescue puts "Error writing file \'#{filename}\'" exit end puts "File \'#{filename}\' successfully saved." else puts 'USAGE: /path/to/script/aurora-tts [text] [filename] [app_id] [app_token]' end
true
63b8048eb9a1e464bd8146076f3b1bb940032fcc
Ruby
kallus/TrafficSim
/model/tcross_e_tile.rb
UTF-8
2,309
2.78125
3
[]
no_license
#done and tested class TcrossETile < Tile def initialize @paths = [] #copy of SW turn entrance_west = lambda do |s| s = s.to_f r = 5.0 if s < 20 then [s, 25] elsif s < 20 + r/2*Math::PI then [20+r*Math.sin((s-20)/r),20+r*Math.cos((s-20)/r)] else [25, 40+r/2*Math::PI-s] end end entrance_south = lambda do |s| s = s.to_f r = 15.0 if s < 20 then [35, s] elsif s < 20 + r/2*Math::PI then [20+r*Math.cos((s-20)/r), 20+r*Math.sin((s-20)/r)] else [40+r/2*Math::PI-s, 35] end end ws = LockablePath.new(entrance_west, 40+2.5*Math::PI, [25,0]) sw = LockablePath.new(entrance_south, 40+7.5*Math::PI, [0,35]) @paths << ws @paths << sw #copy of NW turn entrance_west = lambda do |s| s = s.to_f r = 15.0 if s < 20 then [s, 25] elsif s < 20 + r/2*Math::PI then [20+r*Math.sin((s-20)/r),40-r*Math.cos((s-20)/r)] else [35, 20-r/2*Math::PI+s] end end entrance_north = lambda do |s| s = s.to_f r = 5.0 if s < 20 then [25, Tile.height-s] elsif s < 20 + r/2*Math::PI then [20+r*Math.cos((s-20)/r), 40-r*Math.sin((s-20)/r)] else [40+r/2*Math::PI-s, 35] end end wn = LockablePath.new(entrance_west, 40+7.5*Math::PI, [35,Tile.width]) nw = LockablePath.new(entrance_north, 40+2.5*Math::PI, [0,35]) @paths << wn @paths << nw #copy of vertical ns = LockablePath.new(lambda {|s| [25, Tile.height-s]}, Tile.height, [25,0]) #entrance from north sn = LockablePath.new(lambda {|s| [35, s]}, Tile.height, [35,Tile.height]) #entrance from south @paths << ns @paths << sn sorter = lambda { |a, b| a.number <=> b.number } ws.crossing_paths = [ws, ns].sort! &sorter sw.crossing_paths = [sw, ns, wn, nw].sort! &sorter wn.crossing_paths = [wn, ns, sn, sw].sort! &sorter nw.crossing_paths = [nw].sort! &sorter ns.crossing_paths = [ns, sw, wn, ws].sort! &sorter sn.crossing_paths = [sn, wn].sort! &sorter @start_positions = [] @paths.each do |p| distance = 1 + Car.length while distance <= p.length @start_positions << {:distance => distance, :path => p} distance += Car.length + 2 end end end end
true
747300b898c6e871dbd41a6541908b4811542bd0
Ruby
jayjaybigdog/fakebigdata
/NumberFileOutput.rb
UTF-8
1,104
3.359375
3
[]
no_license
class NumberFileOutput @width = 70 # 70 actual characters per line @leftPadding = 5 # 5 white spaces on left side of a line @rightPadding = 5 # 5 white spaces on right side of a line def initialize (width, leftPadding, rightPadding) @width = width @rightPadding = rightPadding @leftPadding = leftPadding end def format (filename, strContent) actualWidth = @width + @leftPadding + @rightPadding length = strContent.length counter = length / @width reminder = length % @width File.open(filename, 'w+') do |f1| for loop in 1..counter do centralPart = strContent[(loop - 1) * @width, @width] oneLine = ' ' * @leftPadding + centralPart + ' ' * @rightPadding f1.puts oneLine end # handle the last line if reminder > 0 tail = strContent[counter * @width, reminder] lastLine = ' ' * @leftPadding + tail f1.puts lastLine end # if statement f1.close end # File.open() end # format method end # end of the class definition
true
845a84fedb5bfd32a9eb6b4e93d71e910ef37143
Ruby
tamouse/elapsed_watch
/lib/elapsed_watch/version.rb
UTF-8
498
3.171875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module ElapsedWatch VERSION = "1.1.0" DESCRIPTION = " Reading a file of events, containing an event name (a string) and a date-time string (yyyy-mm-dd hh:mm(:ss)), print a nice duration since the event (if the event occurs in the past) or until the event (if the event occurs in the future). The impetous for this little program is my wanting to know how long it has been since my last cigarette. " SUMMARY = "Print elapsed time since or until an event in nice human-readable form" end
true
019912d95bb504d11aa773c62c9adf4ec44a95fc
Ruby
mihaibuzgau/pdksync
/lib/pdksync/constants.rb
UTF-8
3,776
2.5625
3
[ "Apache-2.0" ]
permissive
require 'yaml' # @summary # A module used to contain a set of variables that are expected to remain constant across all iterations of the main pdksync module. # @note # Configuration is loaded from `$HOME/.pdksync.yml`. If $HOME is not set, the config_path will use the current directory. # Set PDKSYNC_LABEL to '' to disable adding a label during pdksync runs. module PdkSync # rubocop:disable Style/ClassAndModuleChildren # Constants contains the configuration for pdksync to use module Constants default_config = { namespace: 'puppetlabs', pdksync_dir: 'modules_pdksync', push_file_destination: 'origin', create_pr_against: 'master', managed_modules: 'managed_modules.yml', pdksync_label: 'maintenance', git_platform: :github, git_base_uri: 'https://github.com', gitlab_api_endpoint: 'https://gitlab.com/api/v4' } supported_git_platforms = [:github, :gitlab] config = {} config_path = File.exist?('pdksync.yml') ? 'pdksync.yml' : "#{ENV['HOME']}/.pdksync.yml" # pdksync config file must exist, not be empty and not be an empty YAML file if File.exist?(config_path) && YAML.load_file(config_path) && !YAML.load_file(config_path).nil? custom_config = YAML.load_file(config_path) config[:namespace] = custom_config['namespace'] ||= default_config[:namespace] config[:pdksync_dir] = custom_config['pdksync_dir'] ||= default_config[:pdksync_dir] config[:push_file_destination] = custom_config['push_file_destination'] ||= default_config[:push_file_destination] config[:create_pr_against] = custom_config['create_pr_against'] ||= default_config[:create_pr_against] config[:managed_modules] = custom_config['managed_modules'] ||= default_config[:managed_modules] config[:pdksync_label] = custom_config['pdksync_label'] ||= default_config[:pdksync_label] config[:git_platform] = custom_config['git_platform'] ||= default_config[:git_platform] config[:git_base_uri] = custom_config['git_base_uri'] ||= case config[:git_platform] when :gitlab 'https://gitlab.com' else default_config[:git_base_uri] end config[:gitlab_api_endpoint] = custom_config['gitlab_api_endpoint'] ||= default_config[:gitlab_api_endpoint] else config = default_config end NAMESPACE = config[:namespace].freeze PDKSYNC_DIR = config[:pdksync_dir].freeze PUSH_FILE_DESTINATION = config[:push_file_destination].freeze CREATE_PR_AGAINST = config[:create_pr_against].freeze MANAGED_MODULES = config[:managed_modules].freeze PDKSYNC_LABEL = config[:pdksync_label].freeze GIT_PLATFORM = config[:git_platform].downcase.to_sym.freeze GIT_BASE_URI = config[:git_base_uri].freeze GITLAB_API_ENDPOINT = config[:gitlab_api_endpoint].freeze ACCESS_TOKEN = case GIT_PLATFORM when :github ENV['GITHUB_TOKEN'].freeze when :gitlab ENV['GITLAB_TOKEN'].freeze end # Sanity checks unless supported_git_platforms.include?(GIT_PLATFORM) raise "Unsupported Git hosting platform '#{GIT_PLATFORM}'."\ " Supported platforms are: #{supported_git_platforms.join(', ')}" end if ACCESS_TOKEN.nil? raise "Git platform access token for #{GIT_PLATFORM.capitalize} not set"\ " - use 'export #{GIT_PLATFORM.upcase}_TOKEN=\"<your token>\"' to set" end end end
true
a7295d73ed84ebeb7ee911256f224a60c02d36d8
Ruby
gadgetguy82/gym_project
/db/seeds.rb
UTF-8
4,087
2.796875
3
[]
no_license
# require("pry") require_relative("../models/booking") require_relative("../models/gym_class") require_relative("../models/room") require_relative("../models/member") require_relative("../models/instructor") require_relative("../models/gym") Booking.delete_all GymClass.delete_all Room.delete_all Member.delete_all Instructor.delete_all Gym.delete_all instructor_quantity = 10 member_quantity = 20 room_quantity = 5 gym_class_quantity = 10 booking_quantity = 15 gym = Gym.new( { "name" => "Agile Fitness", "start_peak" => "16:00", "stop_peak" => "19:00" } ) gym.save first_names = ["Andrew", "Betty", "Charles", "Daniella", "Eric", "Frieda", "Greg", "Helga", "Ian", "Jane", "Kevin", "Laura", "Matthew", "Natalie", "Oscar", "Pauline", "Richard", "Sarah", "Thomas", "Una", "Victor", "Wendy"] last_names = ["Anderson", "Bailey", "Christie", "Dyer", "Egerton", "Fogel", "Glass", "Henley", "Innes", "Johnson", "Kent", "Little", "McIntyre", "Nichols", "Osbourne", "Pickles", "Quirke", "Raimi", "Stevenson", "Trent"] instructors = [] instructor_quantity.times{ instructors.push( Instructor.new( { "first_name" => first_names.sample, "last_name" => last_names.sample } ) ) } instructors.each{|instructor| instructor.save} days = (1..28).to_a months = (1..12).to_a years = (1960..2000).to_a streets = ["23 Springvalley Terrace", "14 Mortonhall Crescent", "35 Muirhouse Road"] cities = ["Edinburgh", "Glasgow", "Stirling"] postcodes = ["EH4 6HD", "G1 4BX", "FK4 7LY"] phones = ["0131 223 4455", "0131 210 8732", "0131 430 9938"] memberships = ["Premium", "Standard"] members = [] member_quantity.times{ members.push( Member.new( { "first_name" => first_names.sample, "last_name" => last_names.sample, "date_of_birth" => "#{days.sample}/#{months.sample}/#{years.sample}", "street" => streets.sample, "city" => cities.sample, "postcode" => postcodes.sample, "phone" => phones.sample, "membership" => memberships.sample } ) ) } members.each{|member| member.save} names = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "Indigo"] capacities = [10, 20, 30, 40, 50] index = 0 rooms = [] room_quantity.times{ rooms.push( Room.new( { "name" => names[index], "capacity" => capacities.sample } ) ) index += 1 } rooms.each{|room| room.save} types = ["Body Balance", "Calisthenics", "Core Conditioning", "Judo", "Karate", "Pilates", "Step Aerobics", "Yoga", "Zumba"] year = 2019 times = ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00"] durations = ["1 hour", "50 minutes", "40 minutes", "30 minutes"] gym_classes = [] gym_classes.push( GymClass.new( { "type" => types.sample, "start_date" => "2019-04-23", "start_time" => times.sample, "duration" => durations.sample, "room_id" => rooms.sample.id, "instructor_id" => instructors.sample.id } ) ) gym_classes.push( GymClass.new( { "type" => types.sample, "start_date" => "2019-06-23", "start_time" => "11:00", "duration" => durations.sample, "room_id" => rooms.sample.id, "instructor_id" => instructors.sample.id } ) ) gym_class_quantity.times{ gym_classes.push( GymClass.new( { "type" => types.sample, "start_date" => "#{year}-#{months.sample}-#{days.sample}", "start_time" => times.sample, "duration" => durations.sample, "room_id" => rooms.sample.id, "instructor_id" => instructors.sample.id } ) ) } gym_classes.each do |gc| if gc.check_room_free && gc.check_instructor_free gc.save end end bookings = [] booking_quantity.times{ bookings.push( Booking.new( { "member_id" => members.sample.id, "gym_class_id" => gym_classes.sample.id } ) ) } bookings.each do |booking| booking.save booking.gym_class.booked_space end # binding.pry # nil
true
a2097e4733e440019cf93020c191fbeed9c0b1b4
Ruby
wearit/dagnabit
/lib/dagnabit/vertex/settings.rb
UTF-8
1,508
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require File.join(File.dirname(__FILE__), %w(.. vertex)) module Dagnabit::Vertex ## # Contains parameters that can be customized on a per-vertex-model basis. module Settings ## # The name of this vertex's edge model. # # @return [String] attr_accessor :edge_model_name ## # The edge model associated with a vertex model. # # @return [Class] the edge model def edge_model edge_model_name.constantize end ## # The edge table used by connectivity queries. Equivalent to # # edge_model.table_name # # @return [String] the name of the edge table def edge_table edge_model.table_name end ## # Sets the name of the edge model associated with a vertex. # # {#edge_model} uses ActiveSupport's `constantize` method to look up the # model from `edge_model_name`. # # @param [String] edge_model_name the name of the edge model to use # @return [void] def connected_by(edge_model_name) self.edge_model_name = edge_model_name end ## # This callback ensures that whenever a class that extends Settings is # inherited, the settings for the superclass are passed to the subclass. # # This callback executes any previously-defined definitions of `inherited` # beforee executing its own code. # # @param [Class] subclass the descendant class def inherited(subclass) super subclass.connected_by(edge_model_name) end end end
true
7a0f3fa51736eb1fd0d5f2b1cee111158415e338
Ruby
Peacepapi/Aggron
/test/models/tool_test.rb
UTF-8
949
2.609375
3
[]
no_license
require "test_helper" class ToolTest < ActiveSupport:: TestCase def setup @tool = Tool.new(name: "Drill", description: "Yo, this things really work.") end test "user_id should be present" do @tool.user_id = nil assert_not @tool.valid? end test "tooltype should be present" do @tool.tooltype_id = nil assert_not @tool.valid? end test "name should be present" do @tool.name = " " assert_not @tool.valid? end test "name should not be too long" do @tool.name = "a" * 101 assert_not @tool.valid? end test "name should not be too short" do @tool.name = "a" * 3 assert_not @tool.valid? end test "description should be present" do @tool.description = " " assert_not @tool.valid? end test "description should not be too long" do @tool.description = "a" * 255 assert_not @tool.valid? end test "description should not be too short" do @tool.description = "a" * 9 assert_not @tool.valid? end end
true
2892e399bcdc9d63b90145e7cb2230a022844784
Ruby
lukedemi/advent-of-code-2018
/day-20/part-2.rb
UTF-8
1,659
3.0625
3
[]
no_license
#!/usr/bin/env ruby file_path = File.expand_path("../input.txt", __FILE__) INPUT = File.read(file_path).chomp MAP = Hash.new D = { 'E' => [1,0], 'W' => [-1,0], 'S' => [0,1], 'N' => [0,-1] } def p max_y = MAP.keys.max_by { |c| c.last }.last + 1 min_y = MAP.keys.min_by { |c| c.last }.last - 1 max_x = MAP.keys.max_by { |c| c.first }.first + 1 min_x = MAP.keys.min_by { |c| c.first }.first - 1 (min_y..max_y).each do |y| print "#{y}\t" (min_x..max_x).each_with_index do |x| if MAP[[x,y]].nil? print "#" else print MAP[[x,y]] end end print "\n" end end def dir_me(direction, coords) [coords.first + direction.first, coords.last + direction.last] end start = [] coords = [0,0] left_off = [] INPUT.chars.each do |i| if i =~ /(N|S|E|W)/ coords = dir_me(coords, D[i]) MAP[coords] = "|" if i =~ /(E|W)/ MAP[coords] = "-" if i =~ /(N|S)/ coords = dir_me(coords, D[i]) MAP[coords] = "." elsif i == "^" start = coords MAP[coords] = "X" elsif i == "(" left_off << coords elsif i == "|" coords = left_off.last elsif i == ")" coords = left_off.pop end rescue binding.pry end possible = [] max = 0 queue = [[start, 0]] chain = { start => nil } loop do break if queue.empty? coords, rooms = queue.shift moves = D.values.map { |vm| [coords.first+vm.first, coords.last+vm.last] } moves.each do |c| next if chain.key?(c) || MAP[c].nil? chain[c] = coords max = rooms + 1 possible << coords if (max/2) >= 1000 queue << [c, rooms + 1] end end puts possible.uniq.select { |p| MAP[p] =~ /(\||\-)/ }.length puts max/2
true
4083daf21e72d5f1cecdd7a5ab7685ee142d4f7e
Ruby
NickPapayiannakis/ruby_experiments
/stock_picker.rb
UTF-8
851
3.734375
4
[]
no_license
def stock_picker(array_of_prices) highest_profit, current_profit, buy_price, sell_price, buy_day, sell_day = 0 array_of_prices.each_index do |day| current_sell_price = array_of_prices[day] current_buy_price = array_of_prices.first(day).min if current_sell_price != array_of_prices.first current_profit = current_sell_price - current_buy_price if current_profit > highest_profit buy_price, sell_price = current_buy_price, current_sell_price buy_day, sell_day = array_of_prices.rindex(buy_price), array_of_prices.rindex(sell_price) highest_profit = sell_price - buy_price end end end puts "buy on day #{buy_day + 1} for $#{buy_price} | sell day #{sell_day + 1} for $#{sell_price}" end stock_picker([100,3,46,6,4,1,5])
true
c9bf3e6df570014f6ef8958d74626f951509b4d7
Ruby
autopp/dominion-2nd-lap
/border_guard.rb
UTF-8
5,134
3.265625
3
[]
no_license
require_relative 'tactic' class BorderGuard < Tactic BG = :bg # partner returns partner of this tactic # # @return [Symbol] # def partner raise NotImplementedError end def gen_decks with_combination_of_estates(12) do |factory, other_indices| other_indices.permutation(2).map do |others| factory.new_deck do |deck| deck[others[0]] = BG deck[others[1]] = partner end end end end def split_to_hands(deck) hands = case deck.find_index(BG) when 0...5 [choose_border_guard(deck[0...7]).sort!, deck[7...12].sort!] when 5...10 [deck[0...5].sort!, choose_border_guard(deck[5...12]).sort!] else [deck[0...5].sort!, deck[5...10].sort!] end sum = hands.map(&:size).reduce(&:+) raise "#{sum} != 11 && #{sum} != 10" if sum != 11 && sum != 10 hands end # choose_border_guard reutnrs hand after choosing # # @param [Array<Symbol>] # # @return [Array<Symbol>] # def choose_border_guard(_hand) raise NotImplementedError end # Helper # choose_one chooses from revealed according to the priority of order # # @param [Array<Symbol>] revealed # @param [Array<Symbol>] order # # @return [Symbol] # def choose_one(revealed, order) found = order.find { |x| revealed.include?(x) } found || raise("revealed: #{revealed}, order: #{order}") end end class BorderGuardWithSilver < BorderGuard def title '国境警備隊・銀貨で4ターン目までに……' end def partner SILVER end def choose_border_guard(hand) revealed = hand[5...7] hand = hand[0...5] choice = choose_one(revealed, [SILVER, COPPER, ESTATE]) [*hand, choice] end include SimulateTurnWithBaseCoinOnly def simulate(deck) hand3, hand4 = deck t3 = simulate_turn(hand3) t4 = simulate_turn(hand4) result_of_at_least_onces(t3, t4, 5, 6) end def topics { **topic_for_at_least_once_5, **topic_for_at_least_once_6(geq: false) } end end class BorderGuardWithSalvager < BorderGuard SALVAGER = :salvager def title '国境警備隊・引揚水夫で4ターン目までに……' end def partner SALVAGER end def choose_border_guard(hand) revealed = hand[5...7] hand = hand[0...5] choice = if hand.include?(SALVAGER) && !hand.include?(ESTATE) choose_one(revealed, [ESTATE, SILVER, COPPER]) elsif !hand.include?(SALVAGER) && hand.include?(ESTATE) choose_one(revealed, [SALVAGER, SILVER, COPPER, ESTATE]) else choose_one(revealed, [SILVER, COPPER, ESTATE, SALVAGER]) end [*hand, choice] end def simulate_turn(hand) coin = sum_of_coin(hand) trashing_estate = false if hand.include?(SALVAGER) && hand.include?(ESTATE) coin += 2 trashing_estate = true end over4_buy2 = trashing_estate && coin >= 4 { coin: coin, trashing_estate: trashing_estate, over4_buy2: over4_buy2 } end def simulate(deck) hand3, hand4 = deck t3 = simulate_turn(hand3) t4 = simulate_turn(hand4) { **result_of_at_least_once_5(t3, t4), trashing_estate: any?(t3, t4, :trashing_estate), trashing_estate_and_at_least_once_5: any?(t3, t4, :trashing_estate) && at_least_once_5?(t3, t4), over4_buy2: any?(t3, t4, :over4_buy2) } end def topics { **topic_for_at_least_once_5, **topic_for_trashing_estate, **topic_for_trashing_estate_and_at_least_once_5, over4_buy2: '4金以上2購入が出る確率' } end end class BorderGuardWithBaron < BorderGuard # @return [Symbol] BARON = :baron def title '国境警備隊・男爵で4ターン目までに……' end def partner BARON end def choose_border_guard(hand) revealed = hand[5...7] hand = hand[0...5] choice = if hand.include?(BARON) && !hand.include?(ESTATE) choose_one(revealed, [ESTATE, SILVER, COPPER]) elsif !hand.include?(BARON) && hand.include?(ESTATE) choose_one(revealed, [BARON, SILVER, COPPER, ESTATE]) else choose_one(revealed, [SILVER, COPPER, ESTATE, BARON]) end [*hand, choice] end def simulate_turn(hand) coin = sum_of_coin(hand) neet = true if hand.include?(BARON) && hand.include?(ESTATE) coin += 4 neet = false end { coin: coin, neet: neet } end def simulate(deck) hand3, hand4 = deck t3 = simulate_turn(hand3) t4 = simulate_turn(hand4) { **result_of_at_least_onces(t3, t4, 5, 6, 7), both_5: both_5?(t3, t4), both_5_and_at_least_once_6: both_5?(t3, t4) && at_least_once_6?(t3, t4), neet: all?(t3, t4, :neet) } end def topics { **topic_for_at_least_once_5, **topic_for_at_least_once_6, **topic_for_at_least_once(7, geq: false), **topic_for_both_5, **topic_for_both_and_at_least_once(5, 6, geq: false), neet: '男爵が沈む、あるいはニート男爵になる確率' } end end BorderGuardWithSilver.new.report puts BorderGuardWithSalvager.new.report puts BorderGuardWithBaron.new.report
true
a93bd17cd929c56e0694c25a00fe0b56a774d34a
Ruby
StephenVarela/collections_and_iterations
/exercise5.rb
UTF-8
1,942
3.640625
4
[]
no_license
def separate() puts "-------------------------------------------------" end fav_colors = ['red', 'blue', 'green', 'yellow'] ages = [22,24,32,19,7] coin_flips = ['heads', 'tails', 'heads', 'heads', 'heads'] fav_artists = ['Dream Theater', 'Metallica', 'Motley Crue'] fav_colors_sym = [:red, :blue, :green, :yellow] # Create a hash for each item below that contains the given information: # # three words and their definitions # your favourite movie names and their year of creation # three cities of the world and their population # the names of your siblings/cousins/friends and their age dictionary = { :search => 'to go or look through a place to find something missing or lost', :dive => 'to plunge into water head first', :study => 'application of the mind to the aquisition of knowledge' } movies = { :Lord_of_the_Rings => 2001, :Star_Wars => 2008, :Inception => 2010 } cities = { :Toronto => 2809000, :Perth => 1671000, :Mumbai => 18410000 } relatives = { :Simonne => 21, :Shannon => 24, :Joshua => 18 } # Find the sum total of the population in the hash of cities. total_population = 0 cities.each do |city, pop| total_population += pop end puts "Total population: #{total_population}" separate # Using your hash containing the names of your family and friends with their ages, print out one of two messages for each depending on their age. For example: # Martha is old. # Stewart is young. # Holly is young. relatives.each do |name, age| if age > 20 puts "#{name} is old" else puts "#{name} is young" end end separate # Print out the last two colours in your array of favourite colours. puts fav_colors[-2..-1] separate # Increase by 1 the age of everyone in your array of ages. Print it out. ages.map! do |age| age += 1 end puts ages separate # Add two new colours to your array of favourite colours fav_colors = fav_colors + ['purple', 'black'] puts fav_colors separate
true
b816c9a8a89ca3830ed97b48908f4742aa062da0
Ruby
Reti500/NewsT
/hola.rb
UTF-8
396
3.15625
3
[]
no_license
@tag = [] @str = "#Esto es un #Hashtag de prueba #AprendoAProgramar#Ruby".split(" ") # @str.each do |cad| # if cad.include? "#" # @tag << cad.split( /#(\S+)/ ).last # end # end def getTags( palabras, tags ) palabras.each do |p| if p.include? "#" minitag = p.split( /#(\S+)/ ).last unless minitag.include? "#" tags << minitag end end end end getTags( @str, @tag ) @tag
true
1ddfc9edceb33e343563469e2586823116de6427
Ruby
gsamokovarov/carmine
/lib/carmine/version.rb
UTF-8
359
2.609375
3
[ "MIT" ]
permissive
class Carmine module Version Major, Minor, Patch = File.read(File.expand_path('../../../VERSION', __FILE__)).split('.') end class << self # Public: The version of the client. # # Returns a String of the dot joined version parts. def version [Version::Major, Version::Minor, Version::Patch].join('.') end end end
true
bc9ef1c65662b5bf89b9a8f3ee9fe346bcd19f26
Ruby
wthompson92/cross_check
/lib/team_module.rb
UTF-8
7,867
3.015625
3
[]
no_license
require 'pry' module TeamModule def team_info(id) team = teams.find{|x| x.team_id == id} { "team_id" => team.team_id, "franchise_id" => team.franchise_id, "short_name" => team.short_name, "team_name" => team.team_name, "abbreviation" => team.abbreviation, "link" => team.link} end def games_played(team_id) games.find_all do |game| game.away_team_id == team_id || game.home_team_id == team_id end end def total_seasons(team_id) seasons = [] games_played(team_id).each{ |game| seasons << game.season } seasons.uniq end def games_played_by_season(team_id, postseason) games_played(team_id).find_all do |game| game.type == postseason end.group_by do |game| game.season end.transform_values do |games_in_season| games_in_season.length end end def games_shared(team_id) sg = [] rivals(team_id).each do |rival| games.each do |game| if game.away_team_id == team_id && game.home_team_id == rival sg << game elsif game.away_team_id == rival && game.home_team_id == team_id sg << game end end end sg end def win_perc_by_season(team_id) win_perc_by_season_(team_id, "") end def we_won_this_game(team_id,game) away_won = game.away_team_id == team_id && game.outcome.include?("away") home_won = game.home_team_id == team_id && game.outcome.include?("home") away_won || home_won end def win_perc_by_season_(team_id, postseason) win_percent_by_season = {} total_seasons(team_id).find_all do |season| wins = 0 games_by_season = 0 games_played(team_id).find_all do |game| if game.season == season && game.type.include?(postseason) games_by_season += 1 wins += 1 if we_won_this_game(team_id,game) end end winning_percentage = wins.to_f / games_by_season if !winning_percentage.to_f.nan? win_percent_by_season.store(season, winning_percentage) end end win_percent_by_season end def best_season(team_id) winning_percentages = win_perc_by_season(team_id) winning_percentages.max_by { |season, win_percent| win_percent }.first end def worst_season(team_id) winning_percentages = win_perc_by_season(team_id) winning_percentages.min_by { |season, win_percent| win_percent }.first end def average_win_percentage(team_id) team_games = games.find_all do |game| game.home_team_id == team_id || game.away_team_id == team_id end team_wins = games.count do |game| we_won_this_game(team_id, game) end (team_wins / team_games.length.to_f).round(2) end def all_goals(team_id) all_goals = [] games_played(team_id).find_all do |game| if game.away_team_id == team_id all_goals << game.away_goals elsif game.home_team_id == team_id all_goals << game.home_goals end end all_goals end def most_goals_scored(team_id) all_goals(team_id).max end def fewest_goals_scored(team_id) all_goals(team_id).min end def team_jazz(team_id) @teams.find do |team| team.team_id == team_id end end def team_outcomes(team_id) outcomes = [] games_played(team_id).each do |game| if game.home_team_id == team_id outcomes << [game.home_goals, game.away_goals] elsif game.away_team_id == team_id outcomes << [game.away_goals, game.home_goals] end end return outcomes end def biggest_team_blowout(team_id) team_outcomes(team_id).map do |outcome| outcome[0] - outcome[1] end.max end def worst_loss(team_id) team_outcomes(team_id).map do |outcome| outcome[1] - outcome[0] end.max end def total_goals_scored(team_id, postseason) total_goals_by_season = {} total_seasons(team_id).each do |season| goals = [] games_played(team_id).find_all do |game| if game.season == season if game.type.include?(postseason) && game.away_team_id == team_id goals << game.away_goals elsif game.type.include?(postseason) && game.home_team_id == team_id goals << game.home_goals end end end total_goals_by_season[season] = goals.sum end total_goals_by_season end def total_goals_scored_against(team_id, postseason) total_goals_against_by_season = {} total_seasons(team_id).each do |season| goals = [] games_played(team_id).find_all do |game| if game.season == season if game.type.include?(postseason) && game.away_team_id == team_id goals << game.home_goals elsif game.type.include?(postseason) && game.home_team_id == team_id goals << game.away_goals end end end total_goals_against_by_season[season] = goals.sum end total_goals_against_by_season end def average_goals_scored(team_id, postseason) average = {} total_goals_scored(team_id, postseason).each do |season, goals| my_games = games_played_by_season(team_id, postseason)[season].to_f if my_games == 0 average[season] = 0.0 else average[season] = (goals / my_games).round(2) end end average end def average_goals_against(team_id, postseason) average = {} total_goals_scored_against(team_id, postseason).each do |season, goals| my_games = games_played_by_season(team_id, postseason)[season].to_f if my_games == 0 average[season] = 0.0 else average[season] = (goals / my_games).round(2) end end average end def team_stats_for_game(team_id) @game_teams.find_all{ |game| game.team_id == team_id } end def results_by_rival(team_id) games = team_stats_for_game(team_id) against{|hash,other_dudes| hash[other_dudes] = {win: 0, lose: 0}} games.each do |gamess| other_dudes = @game_teams.find do |game| game.game_id == gamess.game_id && game.team_id != gamess.team_id end.team_id outcome = gamess.won ? :win : :lose against[other_dudes][outcome] += 1 end return against end def favorite_opponent against = results_by_rival(team_id) fav_rival = against.max_by do |other_dudes, game_stats| stats[:win] / stats[:lose].to_f end[0] get_team(fav_rival).team_name end def rival #floats are the worst oh floats are the worst! If i see Nan ever again itll be too soon against = results_by_rival(team_id) rival_id = against.min_by do |other_dudes, game_stats| stats[:win] / stats[:lose].to_f end[0] get_team(rival_id).team_name end def head_to_head #I hate this method so much oh good god. I hate you please die in a fire. heads = {} results_by_rival(team_id).each do |other_dudes_id,outcome| other_name = team_jazz(other_id).team_name games_played = outcome[:win] + outcome[:loss].to_f heads[other_name] = (outcome[:win] / games_played).round(2) end heads end def summary(team_id, postseason, season) { win_percentage: win_perc_by_season_(team_id, postseason)[season].to_f.round(2), total_goals_scored: total_goals_scored(team_id, postseason)[season], total_goals_against: total_goals_scored_against(team_id, postseason)[season], average_goals_scored: average_goals_scored(team_id, postseason)[season], average_goals_against: average_goals_against(team_id, postseason)[season] } end def seasonal_summary(team_id) summary = {} total_seasons(team_id).each do |season| summary[season] = { regular_season: summary(team_id, "R", season), postseason: summary(team_id, "P", season) } end return summary end end
true
ea045c7d87a0b10327a14aee6e6a43809bb7af15
Ruby
dlaguerta/FarMar
/specs/product_spec.rb
UTF-8
1,956
3
3
[]
no_license
require_relative 'spec_helper' module FarMar describe Product do describe "#initialize" do let(:product) { Product.new(23, "milk", 112) } it "should create an instance of a product" do product.must_be_instance_of(Product) end #end initialize method end describe "self.all" do let(:products) { Product.all } it "should create an array of instances of markets through the CSV file" do Product.all.must_be_kind_of(Hash) end end describe "self.find(id)" do let(:foots) { Product.find(12) } it "should raise an error if a number is not passed" do proc { Product.find('A') }.must_raise(ArgumentError) end it "should return instance of a product by its product id" do foots.id.must_equal(12) end end #end self.find method describe "#vendor" do let (:heavy_chicken) {Product.find(3)} it "should return the vendor instance that matches the product's vendor id" do heavy_chicken.vendor.id.must_equal(2) end end #end vendor spec describe "#sales" do let(:products) { Product.find(4) } #the product with an id of 4 has 8 sales it "should return a collection of sales instances for the specific product" do # puts products.sales products.sales.must_be_instance_of(Hash) end it "should return the exact number of sales related to that product" do products.sales.length.must_equal(8) end end #end sales spec describe "#number_of_sales" do let(:products) { Product.find(4) } it "should return a number of times the product has sold" do products.number_of_sales.must_equal(8) end end describe "self.by_vendor(vendor_id)" do it "should list all products by vendor id" do all = FarMar::Product.by_vendor(5) all.length.must_equal(3) end end end #end Product end #end module
true
506cb224a577d554329bd8e2a33f168a502cafc0
Ruby
renaudbedard/ludivine
/test/test_health.rb
UTF-8
1,331
2.96875
3
[]
no_license
#!/bin/env ruby # encoding: utf-8 require 'coveralls' Coveralls.wear! require 'minitest/autorun' require 'memory' require_relative '../answer' class TestHealth < Minitest::Test def setup require_relative '../module.health' @@memory = HealthMemoryTest.new() end def test_health_health answer = Answer.new("health", "health", "maxdeviant", "health", "theartificiallounge", @@memory) health = answer.health() assert_equal "@maxdeviant: You currently have 7 health.", health answer = Answer.new("health", "health", "aliceffekt", "health", "theartificiallounge", @@memory) health = answer.health() assert_equal "@aliceffekt: You are _dead_.", health end def test_health_all answer = Answer.new("health", "health", "maxdeviant", "health all", "theartificiallounge", @@memory) all = answer.all() assert_equal true, (all.instance_of? String) end end class HealthMemoryTest < Memory attr_reader :memory def initialize @memory = [ ["ludivine", "health maxdeviant", "7"], ["ludivine", "health aliceffekt", "0"], ] end def load(query) return @memory.find_all { |m| m[1].include? query } end def save(owner, key, value) end end
true
0c57e4b97ba79e93fce8232e8c8772c7557192fa
Ruby
thestokkan/RB100
/exercises_ruby_basics/methods/make_and_model.rb
UTF-8
663
4.75
5
[]
no_license
=begin Make and Model Using the following code, write a method called car that takes two arguments and prints a string containing the values of both arguments. car('Toyota', 'Corolla') Expected output: Toyota Corolla =end def car(make, model) puts make + ' ' + model end car('Toyota', 'Corolla') =begin Further Exploration Remove the #puts call from the car method. Modify your program so it still prints the result. How do the return values of car differ with and without the #puts? =end def car(make, model) make + ' ' + model end puts car('Toyota', 'Avensis') # With #puts, the car method returns nil. Without #puts, it returns the string.
true
d1064aa7e2fc5eab79c2b0bb763bf3881f89ee64
Ruby
cristylk/weather-app
/weather.rb
UTF-8
1,365
3.109375
3
[]
no_license
require 'yahoo_weatherman' require 'sinatra' def weatherman(user_location) client = Weatherman::Client.new celsius_result = client.lookup_by_location(user_location).condition['temp'] fahrenheit_result = ((celsius_result * 9) / 5) + 32 end def conditions(user_location) client = Weatherman::Client.new client.lookup_by_location(user_location).condition['text'] end get '/' do # location = params[:location] # your_location = get_location(location) # @message = weatherman(your_location) # @conditions = conditions(your_location) # "The temperature is #{@message} degrees Fahrenheit. It is #{@conditions}" "#{@message}" erb :index end post '/weather' do @post = params[:post] ['location'] @temperature = weatherman(@post) @conditions = conditions(@post) "#{@weather}" "#{@conditions}" if (@conditions == 'Sunny' || @conditions == 'Sun') erb :sunny elsif (@conditions == 'Cloudy'|| @conditions == 'Mostly Cloudy' || @conditions == 'Partly Cloudy') erb :cloudy elsif (@conditions == 'Snowy' || @conditions == 'Heavy Snow' || @conditions == 'Blowing Snow') erb :snowy elsif (@conditions == 'Light Rain' || @conditions == 'Showers' || @conditions == 'showers' || @conditions == 'Rain') erb :rainy else erb :default end end
true
820e91eef9b53bd4c64aa046297b22766d3345b1
Ruby
chmodawk/Study_Ruby
/代码块/代码块参数.rb
UTF-8
2,038
3.90625
4
[]
no_license
def total(from, to) result = 0 # upto 方法将整数值按照从小到大的方式取出 from.upto(to) do |num| # 判断变量是否由块赋予 if block_given? # result += 从外部传来的num result += yield(num) else # result += 自身的num result += num end end result end p total 1, 10 p total(1, 10) {|x| x ** 2} # 关于参数数量 def block_args_test yield() yield(1) yield(1, 2, 3) end # yield 的参数个数与块变量的个数是不一样的 puts "通过|a|接收块变量" block_args_test do |a| #=> [nil] 多出一个块变量,被赋值为 nil p [a] #=> [1] 一个块变量也不多,被赋值为 yield 参数1 end #=> [1] 缺少两个块变量,缺少的部分被忽略 puts "通过|a, b, c|接收块变量" block_args_test do |a, b, c| #=> [nil, nil, nil] 多出三个块变量,被赋值为 nil p [a, b, c] #=> [1, nil, nil] 多出两个块变量,被赋值为 nil end #=> [1, 2, 3] 一个块变量也不多,接收全部 yield 参数 # 块变量比较多时,多出来的块变量值为 nil puts "通过|*a|接收块变量" # 用引用接收(相当于方法定义中的 # 接收全部 yield 参数 block_args_test do |*a| #=> [[]] yield 参数为空 p [a] #=> [[1]] yield 参数为1 end #=> [[1, 2, 3]] yield 参数为1, 2, 3 # 由此可见 # 0.yield 是将代码块里内容以类似方法的形式传入代码块定义内的操作符 # 1.当 yield(n) 的参数 n 来自代码块时,会获取代码块块变量进行计算 # 2.当 yield(n) 的参数 n 来自代码块定义时,会将值作为参数赋值给代码块变量 # 3.可以使用引用 *a 接收全部的 yield(n) 参数 n # block_args_test {|块变量| # # 操作} yield 将大括号部分作为方法传入块内部 # end # (详情见图)
true
c3059889a62fafdf74e6ce75b2cd6081bb3ac5d3
Ruby
mostafa-zahran/customer-record-cli
/data_stores/in_memory/stores/user.rb
UTF-8
646
2.546875
3
[]
no_license
require './data_stores/in_memory/in_memory_interface' module DataStores module InMemory module Stores # Implementation of user store for in memory data store class User include DataStores::InMemory::InMemoryInterface def initialize(origin_point) @origin_point = origin_point end def add(user) storage << user if select { |u| u.id == user.id }.empty? end def select(&block) storage.select(&block) end def storage super[:users] ||= {} super[:users][@origin_point] ||= [] end end end end end
true
ca7c4d4bc39b56203301bf712531a9ec45f79f95
Ruby
PaulaPaul/xRails
/learn-rails/app/models/owner.rb
UTF-8
980
3.8125
4
[]
no_license
# owner model file class Owner def name name = "Paula" end def birthdate #this is the big day, on the actual year of birth birthdate = Date.new(1960,12,8) #Date is a pre-made class in Rails but not Ruby end def birthday #this is the big day, in the current year today = Date.today birthday = Date.new(today.year, birthdate.month, birthdate.day) end def countdown today = Date.today if birthday >= today countdown = (birthday - today).to_i else countdown = (birthday.next_year - today).to_i #Date.next_year is a built in method of the Date object end end def age #gives the age you are or will be in the current year today = Date.today if birthday > today #if it's not your birthday yet, subtract one age = today.year - birthdate.year - 1 else age = today.year - birthdate.year end end def age_in_hex today = Date.today age_in_hex = age.to_s(16) end end
true
f3571ef48240595a07a8bb9073e3316f510361ca
Ruby
nathanallen/peoplesorts
/models/DSV.rb
UTF-8
427
3.25
3
[]
no_license
class DSV #delimiter seperated values def self.open(filepath) input = File.read(filepath) rows = input.split(/^/) rows.map do |row| yield(parse(row)) end end def self.delimiter_regex %r{ \,\s # comma | # or \s\|\s # pipe | # or else \s # space }x end private def self.parse(row) row.chomp.split(delimiter_regex) end end
true
6da8ae3a04d7ffa1ef27e5971d900d93be9b1db3
Ruby
TMRahim/Deploy
/lib/match_schedules.rb
UTF-8
3,144
2.984375
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'pry' class Weather def initialize(weather_site) site_html = open(weather_site) @weather_team = Nokogiri::HTML(site_html) end def weather_info @weather_team.css("p.wx-temp").children.first.text end def rain_change @weather_team.css("div.wx-details").first.children.children.children[1].text end end class MlbTeam def initialize(team_website) team_html = open(team_website) @team = Nokogiri::HTML(team_html) end def mlb_against @team.css('#my-teams-table div.span-4 div:nth-child(1) div.span-2 div div div div.overview div.team.team-home div.record h6').text end def next_game "The next game for #{team_name} is " + @team.css("div.mod-container.mod-game.current h4").text + " " +"against" + " " + mlb_against end def team_name @team.css('#sub-branding h1 a b').text end end class NFLTeam def initialize (nfl_team_website) nfl_team_html = open(nfl_team_website) @nfl_team = Nokogiri::HTML(nfl_team_html) end def nfl_against @nfl_team.css('#my-teams-table div.span-4 div:nth-child(1) div.span-2 div div div div.overview div.team.team-away div h6').text end def nfl_next_game "The next game for #{nfl_team_name} is " + @nfl_team.css(".bg-opaque#my-teams-table .mod-container .span-2 .mod-no-footer h4").text + " " + "against" + " "+ nfl_against end def nfl_team_name @nfl_team.css('#sub-branding h1 a b').text end end class SoccerTeam def initialize(soccer_site) soccer_team_html = open(soccer_site) @team_doc = Nokogiri::HTML(soccer_team_html) end def date @team_doc.css('div.team-hdr-item.team-hdr-next h4 span.team-hdr-time').text end def time @team_doc.css('div.team-hdr-item.team-hdr-next table tbody tr td.center a').text end def against opponent = "" team1 = @team_doc.css('div.team-hdr-item.team-hdr-next table tbody tr td:nth-child(1)').text team2 = @team_doc.css('div.team-hdr-item.team-hdr-next table tbody tr td.txtright').text if soccer_team_name == team1 opponent = team2 elsif soccer_team_name == team2 opponent = team1 end opponent end def next_game "The next game for #{soccer_team_name} is on #{time}, #{date} against #{against}" end def soccer_team_name @team_doc.css('div.page-header h1 a abbr span').text end end class Matchdata def get_all_matches barcelona = SoccerTeam.new("http://www1.skysports.com/football/teams/barcelona/fixtures-results") giants = NFLTeam.new('http://espn.go.com/nfl/team/_/name/nyg/new-york-giants') yankees = MlbTeam.new('http://espn.go.com/mlb/team/_/name/nyy/new-york-yankees') test_weather = Weather.new("http://www.weather.com/weather/tenday/New+York+NY+USNY0996") "#{barcelona.next_game} \n #{giants.nfl_next_game } \n #{yankees.next_game}." end def get_weather test_weather = Weather.new("http://www.weather.com/weather/tenday/New+York+NY+USNY0996") "Today weather is #{test_weather.weather_info}F. The chance of raining is #{test_weather.rain_change}." end end
true
d40e783ddcd92f70c9eb04f9da129af8102ef6cf
Ruby
a-straube/address-book
/lib/contact.rb
UTF-8
1,402
3.1875
3
[ "MIT" ]
permissive
class Person @@people = [] attr_accessor :first_name, :last_name, :birthday, :phone, :email, :mailing_address define_method(:initialize) do |attributes| @first_name = attributes.fetch(:first_name) @last_name = attributes.fetch(:last_name) if attributes.has_key?(:birthday) @birthday = attributes.fetch(:birthday) else @birthday = nil end end define_method(:save) do @@people.push(self) end define_singleton_method(:all) do @@people end end class Phone attr_accessor :phone_number, :number_type define_method(:initialize) do |attributes| @phone_number = attributes.fetch(:phone_number) @number_type = attributes.fetch(:number_type) end end class Email attr_accessor :email_address, :email_type define_method(:initialize) do |attributes| @email_address = attributes.fetch(:email_address) @email_type = attributes.fetch(:email_type) end end class MailingAddress attr_accessor :address, :address_line, :city, :state, :zip, :address_type define_method(:initialize) do |attributes| @address_line = attributes.fetch(:address_line) @city = attributes.fetch(:city) @state = attributes.fetch(:state) @zip = attributes.fetch(:zip) @address_type = attributes.fetch(:address_type) @address = [@address_line, @city, @state, @zip].join(", ") end end #
true
cab09dd4efb240c437b2789b348b7cffa330f209
Ruby
fnando/formatted_attributes
/test/formatted_attributes_test.rb
UTF-8
1,164
2.875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "test_helper" class FormattedAttributesTest < Minitest::Test test "sets initial value" do product = Product.new(price: 12_300) assert_equal "123,00", product.formatted_price end test "updates formatted price" do product = Product.new(price: 12_300) assert_equal "123,00", product.formatted_price product.price = 45_600 assert_equal "456,00", product.formatted_price end test "sets formatted value" do product = Product.new(price: 12_300) product.formatted_price = "456,78" assert_equal 45_678, product.price assert_equal "456,78", product.formatted_price product.shipping = 67_800 product.formatted_shipping = "345,67" assert_equal 34_567, product.shipping assert_equal "345,67", product.formatted_shipping assert product.valid? end test "works with non-activerecord classes" do post = Post.new post.text = "hello" assert_equal "<p>hello</p>", post.formatted_text post.formatted_text = "<p>nice</p>" assert_equal "nice", post.text post.text = "cool" assert_equal "<p>cool</p>", post.formatted_text end end
true
f2bd8d9938799c0ab49bf7e6ac6477597f9dbefd
Ruby
srirambtechit/ruby-programming
/ri-immutable-obj.rb
UTF-8
819
4.09375
4
[]
no_license
# Freezing objects : The freeze method in class # prevents you from changing on object, effectively # turning an object into a constant. After we freeze # an object, an attempt to modify it results in # RuntimeError. str = "A simple string" str.freeze # Making it as immutable begin str << "An attempt to modify" rescue => err puts "#{err.class} #{err}" end # The output is => RuntimeError can't modify frozen string # freeze operates on an object referene # not on a variable. This means that any operation # resulting in a new object will work. str = "Original string - " str.freeze str += "attachment" puts str # => Original string - attachment # frozen? a = b = "string1" b.freeze puts a.frozen? # true puts b.frozen? # true a = "string2" puts a puts b puts a.frozen? # false puts b.frozen? # true
true
40d0d14039652c28d01ec115667b0f9e7d6bc1f1
Ruby
mashedkeyboard/zxcvbn-ruby
/lib/zxcvbn/tester.rb
UTF-8
885
2.9375
3
[ "MIT" ]
permissive
require 'zxcvbn/data' require 'zxcvbn/password_strength' module Zxcvbn # Allows you to test the strength of multiple passwords without reading and # parsing the dictionary data from disk each test. Dictionary data is read # once from disk and stored in memory for the life of the Tester object. # # Example: # # tester = Zxcvbn::Tester.new # # tester.add_word_lists("custom" => ["words"]) # # tester.test("password 1") # tester.test("password 2") # tester.test("password 3") class Tester def initialize @data = Data.new end def test(password, user_inputs = []) PasswordStrength.new(@data).test(password, user_inputs) end def add_word_lists(lists) lists.each_pair {|name, words| @data.add_word_list(name, words)} end def inspect "#<#{self.class}:0x#{self.__id__.to_s(16)}>" end end end
true
3c2953f4033c6a99d928c022be96a604b8753713
Ruby
dashotv/flame
/ruby/lib/flame/client.rb
UTF-8
1,363
2.59375
3
[ "MIT", "Apache-2.0" ]
permissive
require 'rest-client' require 'uri' require 'json' module Flame class EmptyResponseError < StandardError; end class BadRequestError < StandardError; end class Client def initialize(url, options = {}) @base = url @options = {}.merge(options) @headers = { content_type: 'application/json', accept: 'application/json', } end def nzbget @nzbget ||= Flame::Nzbget.new("#{@base}/nzbs", @options) end def utorrent @utorrent ||= Flame::Utorrent.new("#{@base}/torrents", @options) end def qbittorrent @qbittorrent ||= Flame::Qbittorrent.new("#{@base}/qbittorrents", @options) end private def request(path, params) url = "#{@base}/#{path}?#{URI.encode_www_form(params)}" opt = { method: :get, url: url, headers: @headers, verify_ssl: false, } # puts "request: #{url}" err = nil begin json = RestClient::Request.execute(opt) rescue RestClient::ExceptionWithResponse => e err = e json = e.response end raise EmptyResponseError.new("empty response") unless json && json != '' parsed = ::JSON.parse(json) raise BadRequestError.new("#{err.message}: #{parsed["error"]}") if err parsed end end end
true
e34976aab792936c6b72a63c21829d1e5f8456b8
Ruby
Unicity/Modules.rb
/unicity/bt/task_status.rb
UTF-8
1,159
2.515625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby ## # Copyright © 2015 Unicity International. # # 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 Unicity module BT module TaskStatus QUIT = -3 FAILED = -2 ERROR = -1 INACTIVE = 0 ACTIVE = 1 SUCCESS = 2 def self.valueOf(value) if value.is_a?(String) value.upcase! if value == "QUIT" return QUIT elsif value == "FAILED" return FAILED elsif value == "INACTIVE" return INACTIVE elsif value == "ACTIVE" return ACTIVE elsif value == "SUCCESS" return SUCCESS else return ERROR end end return value end end end end
true
e9bf6148a8bf383d7583a04394952d887765fe61
Ruby
Snakdoc/Ruby-J2
/exo_17.rb
UTF-8
209
3.6875
4
[]
no_license
puts "Hello visiteur, quel est ton âge?" print ">" age = gets.chomp.to_i age.times do |i| if (age - i == i) puts "Moitié de l'âge"; else puts "Il y a #{age - i} ans tu avais #{i} ans" end end
true
cb09a362bf277bba4bcdcce242aa69bd7087755d
Ruby
raychorn/analytics_logger
/app/controllers/files_controller.rb
UTF-8
1,487
2.65625
3
[]
no_license
require "rubygems" # Feature: Upload files to the server by using HTTP POST requests. # Description: This feature initially is for the PCAP project # Usages: # $curl -F file=@C:\test.txt http://10.100.162.63:8082/files # $curl -k -F file=@test.txt https://sprintcm.analytics.smithmicro.com/files class FilesController < ApplicationController EMPTY_HEADER = {} def create input_file, file_name, output_file, msg = nil input_file = params[:file] # input_file is a File object which has file name & data file_name = input_file.original_filename # return File.basename(input_file_name) # check if input_file exists if File.exists?(input_file) puts file_name + " exists" else puts file_name + " does not exist" msg = "http 404 - file not found" render :text => { :success => false, :error_code => 404, :error_msg=> msg }.to_json, :status => 200 end # the target file output_file = "#{RAILS_ROOT}/public/files/#{file_name}" # write to the target file in bytes File.open(output_file, "wb") do |f| f.write(input_file.read) end # render :text => { :success => true }.to_json render :text => { :success => true }.to_json, :status => 200 end =begin def scp_file(user, host, directory, file_name) cmd = "scp " + file + " " + user + "@" + host + ":" + directory + file_name # puts cmd system(cmd) end =end end
true
1555ead666b336d31734bb48d7c4b4b32045d12d
Ruby
LBelin/Estimate
/lib/Order.rb
UTF-8
297
3.125
3
[]
no_license
class Order def self.worst(current) current.each do |fbcase| estimate = fbcase[0] actual = fbcase[1] score = estimate - actual fbcase[2] = score end sorted_current = current.sort_by {|fbcase|fbcase[2]} end def self.best(current) self.worst(current).reverse! end end
true
3ea9b05d9d76d8e8ded647df76688e0bb9b50792
Ruby
brownjs03/key-for-min-value-online-web-pt-081219
/key_for_min.rb
UTF-8
320
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) low_name = nil low_num = nil name_hash.collect do |name, num| if low_num == nil or num < low_num low_num = num low_name = name end end low_name end
true