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
7ea9e06a2610dc34aa7b9da2a4454a029ce1b464
Ruby
zacsek/paradoxical
/lib/paradoxical/parser.rb
UTF-8
1,306
2.890625
3
[ "MIT" ]
permissive
require 'singleton' require 'citrus' require 'yaml' require 'date' class Hash alias_method :old_at, :[] alias_method :old_at_eq, :[]= def [](key) if key.is_a?(String) && key.start_with?('xp:') begin key = key.gsub('xp:','') path = key.split('/').map { |p| p.to_sym } hash = self path.each { |p| if hash.has_key?(p) hash = hash[p] if hash.is_a?(Array) && hash.first == :multi hash.shift hash = hash.first end else return nil end } hash rescue puts "Error selecting key:#{key}" ap self ap path puts raise end else old_at(key) end end def []=(key, value) if key.is_a?(String) && key.start_with?('xp:') begin key = key.gsub('xp:','') path = key.split('/').map { |p| p.to_sym } hash = self path[0..-2].each { |p| hash = hash[p] } hash[path[-1]] = value rescue puts "K:#{key} V:#{value}" raise end else old_at_eq(key, value) end value end end module Paradoxical class Parser include Singleton def initialize fname = File.join(File.dirname(__FILE__), 'paradoxical.citrus') @citrus = Citrus.load(fname, :consume => false).first end def parse(text) ParadoxicalGrammar.parse(text, :consume => false).value end end end
true
fe17917f1b105215b906db51b18d92eebc805f85
Ruby
seomoz/moz_nav
/spec/support/in_sub_process.rb
UTF-8
287
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module InSubProcess def in_sub_process readme, writeme = IO.pipe pid = Process.fork do readme.close writeme.write yield writeme.close end writeme.close Process.waitpid(pid) return_val = readme.read readme.close return_val end end
true
7a6559a339035bb2a0cd725821d5a538edb24878
Ruby
NicolasJJensen/Terminal-RPG
/Testing/game_object_test.rb
UTF-8
1,584
2.984375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'test/unit' require_relative '../Core/vector' require_relative '../Core/raw_graphic' require_relative '../Core/sprite' require_relative '../Core/animation' require_relative '../Core/game_object' # Tests for the Game class class GameObjectTest < Test::Unit::TestCase def setup graphic = " **** * * * * **** " @graphic = RawGraphic.new(graphic, 7) @sprite = Sprite.new([@graphic], [Vector.new(:x => 2, :y => 3)]) @animation = Animation.new([@sprite], [Vector.new(:x => 2, :y => 3)], 60) @game_object = GameObject.new(@animation, Vector.new(:x => 2, :y => 3)) end def test_animation_initalized assert_equal(@game_object.animation, @animation) end def test_pos_initalized assert_equal(@game_object.pos, Vector.new(:x => 2, :y => 3)) end def test_pos_updating @game_object.move(Vector.new(:x => 2, :y => 4)) assert_equal(@game_object.pos, Vector.new(:x => 4, :y => 7)) assert_equal(@game_object.old, Vector.new(:x => 2, :y => 3)) end def test_width assert_equal(@game_object.width, 8) end def test_height assert_equal(@game_object.height, 10) end def test_collision_true game_object2 = GameObject.new(@animation, Vector.new(:x => 4, :y => 5)) assert(@game_object.collides?(game_object2)) assert(game_object2.collides?(@game_object)) end def test_collision_false game_object2 = GameObject.new(@animation, Vector.new(:x => 15, :y => 15)) assert(!@game_object.collides?(game_object2)) assert(!game_object2.collides?(@game_object)) end end
true
f10b2f5be8094c9ce029c7ae853b544e393a07ac
Ruby
zines-archive/zines
/uninformed/code.2.2/tra/opcodes.rb
UTF-8
13,854
2.703125
3
[]
no_license
### # # Opcodes # ------- # # This module wraps the all the opcodes in the opcode database. # ### module Opcodes def self.opcode_groups opcode_hash end def self.opcode_groups_ary groups = {} opcode_hash.each_pair { |o, g| groups[g] = 1 } groups.keys.sort end def self.opcodes opcode_hash.keys end def self.opcode_hash { "\xff\xe4" => "esp => eip", "\xff\xd4" => "esp => eip", "\x54\xc3" => "esp => eip", "\xff\xe5" => "ebp => eip", "\xff\xd5" => "ebp => eip", "\x55\xc3" => "ebp => eip", "\xff\xe0" => "eax => eip", "\xff\xd0" => "eax => eip", "\x50\xc3" => "eax => eip", "\xff\xe3" => "ebx => eip", "\xff\xd3" => "ebx => eip", "\x53\xc3" => "ebx => eip", "\xff\xe1" => "ecx => eip", "\xff\xd1" => "ecx => eip", "\x51\xc3" => "ecx => eip", "\xff\xe2" => "edx => eip", "\xff\xd2" => "edx => eip", "\x52\xc3" => "edx => eip", "\xff\xe6" => "esi => eip", "\xff\xd6" => "esi => eip", "\x56\xc3" => "esi => eip", "\xff\xe7" => "edi => eip", "\xff\xd7" => "edi => eip", "\x57\xc3" => "edi => eip", "\x58\x58\xc3" => "[esp + 8] => eip", "\x58\x5b\xc3" => "[esp + 8] => eip", "\x58\x59\xc3" => "[esp + 8] => eip", "\x58\x5a\xc3" => "[esp + 8] => eip", "\x58\x5f\xc3" => "[esp + 8] => eip", "\x58\x5e\xc3" => "[esp + 8] => eip", "\x58\x5d\xc3" => "[esp + 8] => eip", "\x58\x5c\xc3" => "[esp + 8] => eip", "\x5b\x58\xc3" => "[esp + 8] => eip", "\x5b\x5b\xc3" => "[esp + 8] => eip", "\x5b\x59\xc3" => "[esp + 8] => eip", "\x5b\x5a\xc3" => "[esp + 8] => eip", "\x5b\x5f\xc3" => "[esp + 8] => eip", "\x5b\x5e\xc3" => "[esp + 8] => eip", "\x5b\x5d\xc3" => "[esp + 8] => eip", "\x5b\x5c\xc3" => "[esp + 8] => eip", "\x59\x58\xc3" => "[esp + 8] => eip", "\x59\x5b\xc3" => "[esp + 8] => eip", "\x59\x59\xc3" => "[esp + 8] => eip", "\x59\x5a\xc3" => "[esp + 8] => eip", "\x59\x5f\xc3" => "[esp + 8] => eip", "\x59\x5e\xc3" => "[esp + 8] => eip", "\x59\x5d\xc3" => "[esp + 8] => eip", "\x59\x5c\xc3" => "[esp + 8] => eip", "\x5a\x58\xc3" => "[esp + 8] => eip", "\x5a\x5b\xc3" => "[esp + 8] => eip", "\x5a\x59\xc3" => "[esp + 8] => eip", "\x5a\x5a\xc3" => "[esp + 8] => eip", "\x5a\x5f\xc3" => "[esp + 8] => eip", "\x5a\x5e\xc3" => "[esp + 8] => eip", "\x5a\x5d\xc3" => "[esp + 8] => eip", "\x5a\x5c\xc3" => "[esp + 8] => eip", "\x5f\x58\xc3" => "[esp + 8] => eip", "\x5f\x5b\xc3" => "[esp + 8] => eip", "\x5f\x59\xc3" => "[esp + 8] => eip", "\x5f\x5a\xc3" => "[esp + 8] => eip", "\x5f\x5f\xc3" => "[esp + 8] => eip", "\x5f\x5e\xc3" => "[esp + 8] => eip", "\x5f\x5d\xc3" => "[esp + 8] => eip", "\x5f\x5c\xc3" => "[esp + 8] => eip", "\x5e\x58\xc3" => "[esp + 8] => eip", "\x5e\x5b\xc3" => "[esp + 8] => eip", "\x5e\x59\xc3" => "[esp + 8] => eip", "\x5e\x5a\xc3" => "[esp + 8] => eip", "\x5e\x5f\xc3" => "[esp + 8] => eip", "\x5e\x5e\xc3" => "[esp + 8] => eip", "\x5e\x5d\xc3" => "[esp + 8] => eip", "\x5e\x5c\xc3" => "[esp + 8] => eip", "\x5d\x58\xc3" => "[esp + 8] => eip", "\x5d\x5b\xc3" => "[esp + 8] => eip", "\x5d\x59\xc3" => "[esp + 8] => eip", "\x5d\x5a\xc3" => "[esp + 8] => eip", "\x5d\x5f\xc3" => "[esp + 8] => eip", "\x5d\x5e\xc3" => "[esp + 8] => eip", "\x5d\x5d\xc3" => "[esp + 8] => eip", "\x5d\x5c\xc3" => "[esp + 8] => eip", "\x5c\x58\xc3" => "[esp + 8] => eip", "\x5c\x5b\xc3" => "[esp + 8] => eip", "\x5c\x59\xc3" => "[esp + 8] => eip", "\x5c\x5a\xc3" => "[esp + 8] => eip", "\x5c\x5f\xc3" => "[esp + 8] => eip", "\x5c\x5e\xc3" => "[esp + 8] => eip", "\x5c\x5d\xc3" => "[esp + 8] => eip", "\x5c\x5c\xc3" => "[esp + 8] => eip", "\xff\x60\x00" => "[reg + offset] => eip", "\xff\x60\x04" => "[reg + offset] => eip", "\xff\x60\x08" => "[reg + offset] => eip", "\xff\x60\x0c" => "[reg + offset] => eip", "\xff\x60\x10" => "[reg + offset] => eip", "\xff\x60\x14" => "[reg + offset] => eip", "\xff\x60\x18" => "[reg + offset] => eip", "\xff\x60\x1c" => "[reg + offset] => eip", "\xff\x60\x20" => "[reg + offset] => eip", "\xff\x63\x00" => "[reg + offset] => eip", "\xff\x63\x04" => "[reg + offset] => eip", "\xff\x63\x08" => "[reg + offset] => eip", "\xff\x63\x0c" => "[reg + offset] => eip", "\xff\x63\x10" => "[reg + offset] => eip", "\xff\x63\x14" => "[reg + offset] => eip", "\xff\x63\x18" => "[reg + offset] => eip", "\xff\x63\x1c" => "[reg + offset] => eip", "\xff\x63\x20" => "[reg + offset] => eip", "\xff\x61\x00" => "[reg + offset] => eip", "\xff\x61\x04" => "[reg + offset] => eip", "\xff\x61\x08" => "[reg + offset] => eip", "\xff\x61\x0c" => "[reg + offset] => eip", "\xff\x61\x10" => "[reg + offset] => eip", "\xff\x61\x14" => "[reg + offset] => eip", "\xff\x61\x18" => "[reg + offset] => eip", "\xff\x61\x1c" => "[reg + offset] => eip", "\xff\x61\x20" => "[reg + offset] => eip", "\xff\x62\x00" => "[reg + offset] => eip", "\xff\x62\x04" => "[reg + offset] => eip", "\xff\x62\x08" => "[reg + offset] => eip", "\xff\x62\x0c" => "[reg + offset] => eip", "\xff\x62\x10" => "[reg + offset] => eip", "\xff\x62\x14" => "[reg + offset] => eip", "\xff\x62\x18" => "[reg + offset] => eip", "\xff\x62\x1c" => "[reg + offset] => eip", "\xff\x62\x20" => "[reg + offset] => eip", "\xff\x67\x00" => "[reg + offset] => eip", "\xff\x67\x04" => "[reg + offset] => eip", "\xff\x67\x08" => "[reg + offset] => eip", "\xff\x67\x0c" => "[reg + offset] => eip", "\xff\x67\x10" => "[reg + offset] => eip", "\xff\x67\x14" => "[reg + offset] => eip", "\xff\x67\x18" => "[reg + offset] => eip", "\xff\x67\x1c" => "[reg + offset] => eip", "\xff\x67\x20" => "[reg + offset] => eip", "\xff\x66\x00" => "[reg + offset] => eip", "\xff\x66\x04" => "[reg + offset] => eip", "\xff\x66\x08" => "[reg + offset] => eip", "\xff\x66\x0c" => "[reg + offset] => eip", "\xff\x66\x10" => "[reg + offset] => eip", "\xff\x66\x14" => "[reg + offset] => eip", "\xff\x66\x18" => "[reg + offset] => eip", "\xff\x66\x1c" => "[reg + offset] => eip", "\xff\x66\x20" => "[reg + offset] => eip", "\xff\x65\x00" => "[reg + offset] => eip", "\xff\x65\x04" => "[reg + offset] => eip", "\xff\x65\x08" => "[reg + offset] => eip", "\xff\x65\x0c" => "[reg + offset] => eip", "\xff\x65\x10" => "[reg + offset] => eip", "\xff\x65\x14" => "[reg + offset] => eip", "\xff\x65\x18" => "[reg + offset] => eip", "\xff\x65\x1c" => "[reg + offset] => eip", "\xff\x65\x20" => "[reg + offset] => eip", "\xff\x64\x24\x00" => "[reg + offset] => eip", "\xff\x64\x24\x04" => "[reg + offset] => eip", "\xff\x64\x24\x08" => "[reg + offset] => eip", "\xff\x50\x00" => "[reg + offset] => eip", "\xff\x50\x04" => "[reg + offset] => eip", "\xff\x50\x08" => "[reg + offset] => eip", "\xff\x50\x0c" => "[reg + offset] => eip", "\xff\x50\x10" => "[reg + offset] => eip", "\xff\x50\x14" => "[reg + offset] => eip", "\xff\x50\x18" => "[reg + offset] => eip", "\xff\x50\x1c" => "[reg + offset] => eip", "\xff\x50\x20" => "[reg + offset] => eip", "\xff\x53\x00" => "[reg + offset] => eip", "\xff\x53\x04" => "[reg + offset] => eip", "\xff\x53\x08" => "[reg + offset] => eip", "\xff\x53\x0c" => "[reg + offset] => eip", "\xff\x53\x10" => "[reg + offset] => eip", "\xff\x53\x14" => "[reg + offset] => eip", "\xff\x53\x18" => "[reg + offset] => eip", "\xff\x53\x1c" => "[reg + offset] => eip", "\xff\x53\x20" => "[reg + offset] => eip", "\xff\x51\x00" => "[reg + offset] => eip", "\xff\x51\x04" => "[reg + offset] => eip", "\xff\x51\x08" => "[reg + offset] => eip", "\xff\x51\x0c" => "[reg + offset] => eip", "\xff\x51\x10" => "[reg + offset] => eip", "\xff\x51\x14" => "[reg + offset] => eip", "\xff\x51\x18" => "[reg + offset] => eip", "\xff\x51\x1c" => "[reg + offset] => eip", "\xff\x51\x20" => "[reg + offset] => eip", "\xff\x52\x00" => "[reg + offset] => eip", "\xff\x52\x04" => "[reg + offset] => eip", "\xff\x52\x08" => "[reg + offset] => eip", "\xff\x52\x0c" => "[reg + offset] => eip", "\xff\x52\x10" => "[reg + offset] => eip", "\xff\x52\x14" => "[reg + offset] => eip", "\xff\x52\x18" => "[reg + offset] => eip", "\xff\x52\x1c" => "[reg + offset] => eip", "\xff\x52\x20" => "[reg + offset] => eip", "\xff\x57\x00" => "[reg + offset] => eip", "\xff\x57\x04" => "[reg + offset] => eip", "\xff\x57\x08" => "[reg + offset] => eip", "\xff\x57\x0c" => "[reg + offset] => eip", "\xff\x57\x10" => "[reg + offset] => eip", "\xff\x57\x14" => "[reg + offset] => eip", "\xff\x57\x18" => "[reg + offset] => eip", "\xff\x57\x1c" => "[reg + offset] => eip", "\xff\x57\x20" => "[reg + offset] => eip", "\xff\x56\x00" => "[reg + offset] => eip", "\xff\x56\x04" => "[reg + offset] => eip", "\xff\x56\x08" => "[reg + offset] => eip", "\xff\x56\x0c" => "[reg + offset] => eip", "\xff\x56\x10" => "[reg + offset] => eip", "\xff\x56\x14" => "[reg + offset] => eip", "\xff\x56\x18" => "[reg + offset] => eip", "\xff\x56\x1c" => "[reg + offset] => eip", "\xff\x56\x20" => "[reg + offset] => eip", "\xff\x55\x00" => "[reg + offset] => eip", "\xff\x55\x04" => "[reg + offset] => eip", "\xff\x55\x08" => "[reg + offset] => eip", "\xff\x55\x0c" => "[reg + offset] => eip", "\xff\x55\x10" => "[reg + offset] => eip", "\xff\x55\x14" => "[reg + offset] => eip", "\xff\x55\x18" => "[reg + offset] => eip", "\xff\x55\x1c" => "[reg + offset] => eip", "\xff\x55\x20" => "[reg + offset] => eip", "\xff\x54\x24\x00" => "[reg + offset] => eip", "\xff\x54\x24\x04" => "[reg + offset] => eip", "\xff\x54\x24\x08" => "[reg + offset] => eip", "\x66\x61\xc3" => "[esp + 0x10] => eip", "\x61\xc3" => "[esp + 0x20] => eip", "\xff\x54\x24\x20" => "[reg + offset] => eip", "\xff\x54\x24\x0c" => "[reg + offset] => eip", "\xff\x54\x24\x10" => "[reg + offset] => eip", "\xff\x54\x24\x14" => "[reg + offset] => eip", "\xff\x54\x24\x18" => "[reg + offset] => eip", "\xff\x54\x24\x1c" => "[reg + offset] => eip", "\xff\x64\x24\x20" => "[reg + offset] => eip", "\xff\x64\x24\x0c" => "[reg + offset] => eip", "\xff\x64\x24\x10" => "[reg + offset] => eip", "\xff\x64\x24\x14" => "[reg + offset] => eip", "\xff\x64\x24\x18" => "[reg + offset] => eip", "\xff\x64\x24\x1c" => "[reg + offset] => eip", "\xff\x20" => "[reg] => eip", "\xff\x23" => "[reg] => eip", "\xff\x21" => "[reg] => eip", "\xff\x22" => "[reg] => eip", "\xff\x27" => "[reg] => eip", "\xff\x26" => "[reg] => eip", "\xff\x24\x24" => "[reg] => eip", "\xff\x10" => "[reg] => eip", "\xff\x13" => "[reg] => eip", "\xff\x11" => "[reg] => eip", "\xff\x12" => "[reg] => eip", "\xff\x17" => "[reg] => eip", "\xff\x16" => "[reg] => eip", "\xff\x14\x24" => "[reg] => eip", "\x58\x58\xc2" => "[esp + 8] => eip", "\x58\x5b\xc2" => "[esp + 8] => eip", "\x58\x59\xc2" => "[esp + 8] => eip", "\x58\x5a\xc2" => "[esp + 8] => eip", "\x58\x5f\xc2" => "[esp + 8] => eip", "\x58\x5e\xc2" => "[esp + 8] => eip", "\x58\x5d\xc2" => "[esp + 8] => eip", "\x58\x5c\xc2" => "[esp + 8] => eip", "\x5b\x58\xc2" => "[esp + 8] => eip", "\x5b\x5b\xc2" => "[esp + 8] => eip", "\x5b\x59\xc2" => "[esp + 8] => eip", "\x5b\x5a\xc2" => "[esp + 8] => eip", "\x5b\x5f\xc2" => "[esp + 8] => eip", "\x5b\x5e\xc2" => "[esp + 8] => eip", "\x5b\x5d\xc2" => "[esp + 8] => eip", "\x5b\x5c\xc2" => "[esp + 8] => eip", "\x59\x58\xc2" => "[esp + 8] => eip", "\x59\x5b\xc2" => "[esp + 8] => eip", "\x59\x59\xc2" => "[esp + 8] => eip", "\x59\x5a\xc2" => "[esp + 8] => eip", "\x59\x5f\xc2" => "[esp + 8] => eip", "\x59\x5e\xc2" => "[esp + 8] => eip", "\x59\x5d\xc2" => "[esp + 8] => eip", "\x59\x5c\xc2" => "[esp + 8] => eip", "\x5a\x58\xc2" => "[esp + 8] => eip", "\x5a\x5b\xc2" => "[esp + 8] => eip", "\x5a\x59\xc2" => "[esp + 8] => eip", "\x5a\x5a\xc2" => "[esp + 8] => eip", "\x5a\x5f\xc2" => "[esp + 8] => eip", "\x5a\x5e\xc2" => "[esp + 8] => eip", "\x5a\x5d\xc2" => "[esp + 8] => eip", "\x5a\x5c\xc2" => "[esp + 8] => eip", "\x5f\x58\xc2" => "[esp + 8] => eip", "\x5f\x5b\xc2" => "[esp + 8] => eip", "\x5f\x59\xc2" => "[esp + 8] => eip", "\x5f\x5a\xc2" => "[esp + 8] => eip", "\x5f\x5f\xc2" => "[esp + 8] => eip", "\x5f\x5e\xc2" => "[esp + 8] => eip", "\x5f\x5d\xc2" => "[esp + 8] => eip", "\x5f\x5c\xc2" => "[esp + 8] => eip", "\x5e\x58\xc2" => "[esp + 8] => eip", "\x5e\x5b\xc2" => "[esp + 8] => eip", "\x5e\x59\xc2" => "[esp + 8] => eip", "\x5e\x5a\xc2" => "[esp + 8] => eip", "\x5e\x5f\xc2" => "[esp + 8] => eip", "\x5e\x5e\xc2" => "[esp + 8] => eip", "\x5e\x5d\xc2" => "[esp + 8] => eip", "\x5e\x5c\xc2" => "[esp + 8] => eip", "\x5d\x58\xc2" => "[esp + 8] => eip", "\x5d\x5b\xc2" => "[esp + 8] => eip", "\x5d\x59\xc2" => "[esp + 8] => eip", "\x5d\x5a\xc2" => "[esp + 8] => eip", "\x5d\x5f\xc2" => "[esp + 8] => eip", "\x5d\x5e\xc2" => "[esp + 8] => eip", "\x5d\x5d\xc2" => "[esp + 8] => eip", "\x5d\x5c\xc2" => "[esp + 8] => eip", "\x5c\x58\xc2" => "[esp + 8] => eip", "\x5c\x5b\xc2" => "[esp + 8] => eip", "\x5c\x59\xc2" => "[esp + 8] => eip", "\x5c\x5a\xc2" => "[esp + 8] => eip", "\x5c\x5f\xc2" => "[esp + 8] => eip", "\x5c\x5e\xc2" => "[esp + 8] => eip", "\x5c\x5d\xc2" => "[esp + 8] => eip", "\x5c\x5c\xc2" => "[esp + 8] => eip", "\x50\xc2" => "eax => eip", "\x53\xc2" => "ebx => eip", "\x51\xc2" => "ecx => eip", "\x52\xc2" => "edx => eip", "\x57\xc2" => "edi => eip", "\x56\xc2" => "esi => eip", "\x55\xc2" => "ebp => eip", "\x54\xc2" => "esp => eip", } end end
true
d21e78b4c8626e3c69c53e40e5a0eebc025d3b49
Ruby
Duosmium/sciolyff-conversions
/csv2sciolyff.rb
UTF-8
2,068
3.09375
3
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true # Kinda converts a specific CSV format to SciolyFF # The sections Tournament and Penalties still need to be added manually # require 'csv' require 'yaml' if ARGV.empty? puts 'needs a file to convert' exit 1 end csv = CSV.read(ARGV.first) events = csv.first.drop(2).map do |csv_event| event = { 'name' => csv_event[/^[^(]+/].strip, 'trial' => csv_event.end_with?('(Trial)'), 'trialed' => csv_event.end_with?('(Trialed)') } event.delete('trial') if event['trial'] == false event.delete('trialed') if event['trialed'] == false event end teams = csv.drop(1).map { |r| r[0..1] }.map do |csv_team| team = { 'school' => csv_team.last[/^[^|(]+/].strip, 'number' => csv_team.first.to_i, 'state' => csv_team.last[/\([A-Z]{2}\)/][/[A-Z]{2}/], 'suffix' => csv_team.last[/\|.+\(/]&.[](1..-2)&.strip } team.delete('suffix') unless team['suffix'] team end placings = csv.drop(1).map do |csv_row| csv_row.drop(2).each_with_index.map do |csv_place, col_index| placing = { 'event' => events[col_index]['name'], 'team' => csv_row.first.to_i, 'place' => csv_place.to_i } if placing['place'] > teams.count placing.store('participated', false) if placing['place'] == teams.size + 1 placing.store('disqualified', true) if placing['place'] == teams.size + 2 placing.delete('place') end placing end end.flatten # Identify and fix placings that are just participations points events.map { |e| e['name'] }.each do |event_name| last_place_placings = placings.select do |p| p['event'] == event_name && p['place'] == teams.count end next if placings.find do |p| p['event'] == event_name && p['place'] == (teams.count - 1) end last_place_placings.each do |placing| placing.store('participated', true) placing.delete('place') end end rep = { 'Events' => events, 'Teams' => teams, 'Placings' => placings } puts YAML.dump(rep)
true
1e8e15e4c802429076ff63861188b18e87a82bb4
Ruby
bubbadog/ruby_book
/loops/loops_exercises.rb
UTF-8
663
4.4375
4
[]
no_license
# 1. Each always returns the original array =begin x = [1, 2, 3, 4, 5] x.each do |a| puts a + 1 end =end # 2. =begin stop = '' while stop != "STOP" puts "Please give me a number: " answer = gets.chomp.to_i puts (answer * 2) puts "Want me to ask you again?" stop = gets.chomp.upcase end =end # 3. =begin family_names = ["Justin", "Ainsley", "Bubba"] family_names.each_with_index do |name, index| puts "#{name} is number ##{index + 1}!" end =end # 4. Recursive countdown puts "Give me a number to countdown from:" start = gets.chomp.to_i def countdown(start) puts start if start > 0 countdown(start -1) end end countdown(start) puts "Liftoff!!!"
true
359331ea8572ea80817e707ca0fb7118e0cc72fc
Ruby
topromulan/ghpalacewalls
/GHPW/quick3d.rb
UTF-8
228
2.75
3
[]
no_license
i = File.new("3dcoorddata", "r") #4 nums per line #ex. #2508 3 2 0 re = /([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/ while l=i.readline re.match(l) puts "goto #{$1}; edit name ( #{$2}. #{$3}. #{$4} )" end
true
3a6ce9962a8076306c04df1fed84d97f583d58b6
Ruby
TomoMayumi/contest
/atcoder/abc242/a.rb
UTF-8
108
2.796875
3
[]
no_license
a,b,c,x=gets.split.map(&:to_i) case when x<=a p 1 when x<=b p c*1.0/(b-a) else p 0 end
true
5c5e83d0c9f0656b0f710e5afb81c8862d8af606
Ruby
ClaudioFloreani/countries
/lib/countries/country/class_methods.rb
UTF-8
5,361
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'unicode_utils/downcase' require 'sixarm_ruby_unaccent' module ISO3166 UNSEARCHABLE_METHODS = [:translations].freeze def self::Country(country_data_or_country) case country_data_or_country when ISO3166::Country country_data_or_country when String, Symbol ISO3166::Country.search(country_data_or_country) else raise TypeError, "can't convert #{country_data_or_country.class.name} into ISO3166::Country" end end module CountryClassMethods FIND_BY_REGEX = /^find_(all_)?(country_|countries_)?by_(.+)/ SEARCH_TERM_FILTER_REGEX = /\(|\)|\[\]|,/ def new(country_data) super if country_data.is_a?(Hash) || codes.include?(country_data.to_s.upcase) end def codes ISO3166::Data.codes end def all(&blk) blk ||= proc { |_alpha2, d| ISO3166::Country.new(d) } ISO3166::Data.cache.map(&blk) end alias countries all def all_translated(locale = 'en') translations(locale).values end def all_names_with_codes(locale = 'en') Country.all.map do |c| lc = (c.translation(locale) || c.name) [lc.respond_to?('html_safe') ? lc.html_safe : lc, c.alpha2] end.sort end def translations(locale = 'en') I18nData.countries(locale.upcase) end def search(query) country = new(query.to_s.upcase) country && country.valid? ? country : nil end def [](query) search(query) end def method_missing(method_name, *arguments) matches = method_name.to_s.match(FIND_BY_REGEX) return_all = matches[1] super unless matches countries = find_by(matches[3], arguments[0], matches[2]) return_all ? countries : countries.last end def respond_to_missing?(method_name, include_private = false) matches = method_name.to_s.match(FIND_BY_REGEX) if matches && matches[3] matches[3].all? { |a| instance_methods.include?(a.to_sym) } else super end end def find_all_by(attribute, val) attributes, lookup_value = parse_attributes(attribute, val) ISO3166::Data.cache.select do |_, v| country = Country.new(v) attributes.any? do |attr| Array(country.send(attr)).any? do |n| lookup_value === cached(n) { parse_value(n) } end end end end def collect_countries_with(query_val, query_method=:alpha2, result_method=:itself) return nil unless [query_method, result_method].map{|e| method_defined? e}.all? all.select{|i| i.send(query_method).include? query_val}.collect{|e| e.send(result_method)} end def collect_likely_states(state_str, result_method=:itself) return nil unless method_defined? result_method all.reject{|e| e.subdivisions.map{|k,v| [k,v.translations]}.to_h.select{|k,v| state_str == k or state_str.in? v.values}.blank?}.map{|e| e.send(result_method)} end def subdivisions(alpha2) @subdivisions ||= {} @subdivisions[alpha2] ||= create_subdivisions(subdivision_data(alpha2)) end def create_subdivisions(subdivision_data) subdivision_data.each_with_object({}) do |(k, v), hash| hash[k] = Subdivision.new(v) end end protected def strip_accents(v) if v.is_a?(Regexp) Regexp.new(v.source.unaccent, 'i') else UnicodeUtils.downcase(v.to_s.unaccent) end end def parse_attributes(attribute, val) raise "Invalid attribute name '#{attribute}'" unless searchable_attribute?(attribute.to_sym) attributes = Array(attribute.to_s) if attributes == ['name'] attributes << 'unofficial_names' # TODO: Revisit when better data from i18n_data # attributes << 'translated_names' end [attributes, parse_value(val)] end def searchable_attribute?(attribute) searchable_attributes.include?(attribute.to_sym) end def searchable_attributes instance_methods - UNSEARCHABLE_METHODS end def find_by(attribute, value, obj = nil) find_all_by(attribute.downcase, value).map do |country| obj.nil? ? country : new(country.last) end end def parse_value(value) value = value.gsub(SEARCH_TERM_FILTER_REGEX, '') if value.respond_to?(:gsub) strip_accents(value) end def subdivision_data(alpha2) file = subdivision_file_path(alpha2) File.exist?(file) ? YAML.load_file(file) : {} end def subdivision_file_path(alpha2) File.join(File.dirname(__FILE__), '..', 'data', 'subdivisions', "#{alpha2}.yaml") end # Some methods like parse_value are expensive in that they # create a large number of objects internally. In order to reduce the # object creations and save the GC, we can cache them in an class instance # variable. This will make subsequent parses O(1) and will stop the # creation of new String object instances. # # NB: We only want to use this cache for values coming from the JSON # file or our own code, caching user-generated data could be dangerous # since the cache would continually grow. def cached(value) @_parsed_values_cache ||= {} return @_parsed_values_cache[value] if @_parsed_values_cache[value] @_parsed_values_cache[value] = yield end end end
true
693960732a4cc1c4cc93c88774ffb3f9d1dac61d
Ruby
nicholaslemay/AdventOfCode2017
/Day8/registers.rb
UTF-8
770
3.015625
3
[]
no_license
class Registers @@registers = Hash.new(0) @@max_ever = 0 def self.process(instructions) instructions.each do |line| target, operation, value, source, comparator, comparison = parse(line) if @@registers[source].send(comparator, comparison.to_i) self.send(operation,target,value.to_i) end @@max_ever = self.max if(self.max > @@max_ever) end end def self.max @@registers.values.max || 0 end def self.max_ever @@max_ever end private def self.parse(line) line.match(/(\w+) (\w+) (-?\d+) if (\w+) (\W{1,2}) (-?\d+)/).captures end def self.inc(name, value) @@registers[name] += value end def self.dec(name, value) @@registers[name] -= value end end
true
2cfbbc162366836b88887548fde11c829c4323be
Ruby
bgrogg/w2d3
/tdd/spec/tdd_exercises_spec.rb
UTF-8
1,536
3.515625
4
[]
no_license
require 'rspec' require 'tdd_exercises' describe "#my_uniq" do let(:array) { [1, 2, 1, 3, 3] } it "return an array" do expect(array.my_uniq).to be_a(Array) end it "it does not modify the original array" do expect(array.my_uniq).to_not be(array) end it "contains only unique elements" do expect(array.my_uniq).to eq([1, 2, 3]) end end describe "#two_sum" do let(:array) { [-1, 0, 2, -2, 1] } let(:one_zero) { [3, 0, 4] } it "returns the indices of elements that add to 0" do expect(array.two_sum).to eq([[0, 4], [2, 3]]) end it "does not return a single zero" do expect(one_zero.two_sum).to eq ([]) end it "each passed element index sorted by smaller element first" do array_res = array.two_sum.first expect(array_res.first).to be < (array_res.last) end it "sorts array of pairs dictionary-wise" do array_first_element = array.two_sum.first[0] array_second_element = array.two_sum.last[0] expect(array_first_element).to be < array_second_element end end describe "#my_transpose" do let(:rows) {[[0, 1, 2],[3, 4, 5],[6, 7, 8]]} it "transposes the matrix" do columns = [[0, 3, 6],[1, 4, 7],[2, 5, 8]] expect(my_transpose(rows)).to eq(columns) end end describe "#stock_picker" do let(:array) { [3, 1, 2, 1, 5, 4] } it "outputs the most profitable pair of buy and sell days" do expect(stock_picker(array)).to eq([1, 4]) end it "does not buy stocks in a crash" do expect(stock_picker([5, 4, 3, 2, 1])).to be_nil end end
true
fc29c9ecaf0a3b035f949a3a86179ac6a08c6929
Ruby
miroosama/countdown-to-midnight-web-010818
/countdown.rb
UTF-8
158
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#write your code here def countdown(num) counter = num while num > 0 puts "#{num} SECONDS!" counter -= 1 end return "HAPPY NEW YEAR!" end end
true
29e345c93d212fe0f03dc059f90c226c83036778
Ruby
randallreedjr/project-euler
/009-special-pythagorean/special_pythagorean.rb
UTF-8
648
3.703125
4
[]
no_license
require 'pry' class SpecialPythagorean def initialize(sum) @sum = sum end def calculate (1..@sum-3).to_a.permutation(2).each do |double| if (double[0] < double[1]) && perfect_square?(double.map{|i| i**2}.inject(&:+)) triple = double + [Math.sqrt(double.map{|i| i**2}.inject(&:+))] if correct_sum?(triple) return triple end end end return [] end def pythagorean?(triple) triple[0] ** 2 + triple[1] ** 2 == triple[2] ** 2 end def correct_sum?(triple) triple.inject(&:+) == @sum end def perfect_square?(number) Math.sqrt(number) ** 2 == number end end
true
a1a5b90e58fde9d50cb03030885fb30be929da2c
Ruby
mehmetgul/LearnRuby
/ExponentMehods.rb
UTF-8
277
3.34375
3
[]
no_license
def pow(base_num, pow_num) result = 1 pow_num.times do |index| result = result * base_num end return result end puts pow(2, 3) def pow1(base_num, pow_num) result = 1 pow_num.times do result = result * base_num end return result end puts pow1(12, 3)
true
522b7ba143674c833539b63804af2eeac80a1e3e
Ruby
DianaE620/Lee_Error
/lee_error.rb
UTF-8
1,129
3.84375
4
[]
no_license
def dummy_encrypt(string) string.reverse.swapcase.gsub(/[aeiou]/, "*") end puts dummy_encrypt("EsteEsMiPassword") == "DROWSSApImS*ETS*" def max_letter_frequency_per_word(sentence) enunciado = sentence.split enunciado = words_longer_than(enunciado, 3) frecuencias = letter_per_word(enunciado, "e") numbers_larger_than(frecuencias) end def words_longer_than(array, num) array.select{ |word| word.length > num } end def letter_per_word(array, letter) array.map { |word| word.count(letter)} end def numbers_larger_than(num_array) num_array.max end puts max_letter_frequency_per_word("entero entrar envase enviar enzima equino equipo erario erguir eriaza eriazo erigir eringe eficientemente electroencefalografía") == 5 # --------- Entendiendo el metodo #def max_letter_frequency_per_word(sentence) #sentence.split.select{|word| word.length > 3}.map{ |w| w.count("e") }.max #end #p max_letter_frequency_per_word("En la escuela aprendimos") #a = "En la escuela aprendimos".split #p a #b = a.select{|palabra| palabra.length > 3} #p b #c = b.map {|palabra| palabra.count("e")} #p c #p c.max
true
4d82170e9d4ccd410401dc45bc6792203e405f40
Ruby
jeanlazarou/swiby
/core/test/manual/combo_test.rb
UTF-8
1,106
2.984375
3
[ "CC-BY-2.5", "BSD-3-Clause" ]
permissive
#-- # Copyright (C) Swiby Committers. All rights reserved. # # The software in this package is published under the terms of the BSD # style license a copy of which has been included with this distribution in # the LICENSE.txt file. # #++ class ComboTest < ManualTest manual 'Combo w/ strings, handler receives strings' do form { title "Combo component / strings" width 200 height 70 combo ["default", "blue", "green", "purple", "red", "yellow"] do |theme| puts theme end visible true } end manual 'Handler receives objects' do class MyData attr_accessor :name def initialize name @name = name end def to_s @name end end form { title "Combo component / objects" width 200 height 70 combo([MyData.new(:a), MyData.new(:b), MyData.new(:c)]) do |data| puts data.name end visible true } end end
true
cd43a22080911e849228cae92cea86cf31ba08f5
Ruby
ninamutty/MediaRanker
/test/models/seinfeld_test.rb
UTF-8
1,191
2.75
3
[]
no_license
require 'test_helper' class SeinfeldTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "Seinfeld Episodes must have a title, season, episode and rank" do assert seinfelds(:peephole).valid? "The Reverse Peephole should be valid" seinfelds(:peephole).title = nil ## This name removal is local to the test data - it doesn't change the fixture assert_not seinfelds(:peephole).valid? "The Reverse Peephole should no longer be valid" seinfelds(:slicer).episode = nil assert_not seinfelds(:slicer).valid? "The Slicer should no longer be valid" end test "Seinfeld Episodes must have a unique title" do assert_not Seinfeld.new(title: "The Slicer", season: 8, episode: 7, description: "Kramer gets into meat slicing; Jerry dates a doctor (Marcia Cross) who isn't impressed with his job; George's new boss is a former adversary.", rank: 54).valid? "A Seinfeld Episode with same title and should not be valid" end test 'Episodes can be upvotes or downvote on' do seinfelds(:peephole).upvote assert_equal seinfelds(:peephole).rank, 64 seinfelds(:peephole).downvote assert_equal seinfelds(:peephole).rank, 63 end end
true
5ae51990cffecc2458e5f06ffeabfcb26e957626
Ruby
Alochner2/com-531-ruby
/ch.14.rb
UTF-8
853
3.734375
4
[]
no_license
toast = Proc.new do puts 'Cheers!' end toast.call toast.call toast.call do_you_like = Proc.new do |good_stuff| puts "I *really* like #{good_stuff}!" end do_you_like.call 'chocolate' do_you_like.call 'Ruby' def maybe_do some_proc if rand(2) == 0 some_proc.call end end def twice_do some_proc some_proc.call some_proc.call end wink = Proc.new do puts '<wink>' end glance = Proc.new do puts '<glance>' end maybe_do wink maybe_do wink maybe_do glance maybe_do glance twice_do wink twice_do glance def compose proc1, proc2 Proc.new do |x| proc2.call(proc1.call(x)) end end square_it = Proc.new do |x| x * x end double_it = Proc.new do |x| x + x end double_then_square = compose double_it, square_it square_then_double = compose square_it, double_it puts double_then_square.call(5) puts square_then_double.call(5)
true
081f8114ad1ae978bfb6be6ee7878bb2f9299f1a
Ruby
Kukmedis/ruby-task
/table.rb
UTF-8
380
2.71875
3
[]
no_license
require '~/ruby/turn' class Table attr_accessor :seats, :players, :smallBlind, :quota, :bigBlind, :lastDealer, :turn def initialize(seats, smallBlind) @seats = seats @smallBlind = smallBlind @bigBlind = smallBlind * 2 @quota = smallBlind * 100 @players = [] @lastDealer = nil end def startTurn @turn = Turn.new(self) @turn end end
true
178cdb224737a662c0051c4f461bd491c9d59674
Ruby
danmoran-pro/flash_cards
/lib/flashcard_runner.rb
UTF-8
264
2.921875
3
[]
no_license
require './lib/card' require './lib/turn' require './lib/deck' require './lib/round' class Flashcard_runner def initialize(argument) @argument = argument end @round = Round.new(@deck) puts Welcome! You're playing with 5 cards. puts "-" * 50 end
true
478f170e05aecd228abaa68479bb8a02e8bad489
Ruby
borgr/l---l
/blank_Quantifier.rb
UTF-8
509
2.953125
3
[]
no_license
require 'treat' include Treat::Core::DSL require_relative 'HelpQuestions' par = get_document #create a blank over a number =begin still quite naive. should enhancing it with names and places be smart, or should they be different functions? =end par.each_sentence do |sent| number = tagged(sent, ["QP", "CD"], [], true, false ) if number question = sent.to_s.sub(number, "_____") puts "Fill the blank: #{question}" puts "Answer: #{number}" puts "**************************************" end end
true
c376420d38e3e73ec4201b926cef1ebda24f9666
Ruby
RazvanCiuca/ActiveRecordLite
/new_attr_accessor.rb
UTF-8
506
3.703125
4
[]
no_license
class Cat def self.new_attr_accessor(*attrs) attrs.each do |attr| #make a getter define_method(attr) do self.instance_variable_get("@#{attr}") end #make a setter define_method("#{attr}=") do |value| self.instance_variable_set("@#{attr}", value) end end end def dooo self.send("name=", 5) end new_attr_accessor :name, :color end cat = Cat.new cat.name = "Sally" cat.color = "brown" p cat.name p cat.color cat.dooo p cat.name
true
cdbc97d70877cb5499a2c6adb2b99d3083d13e06
Ruby
dburt/ankiverse
/ankiverse.rb
UTF-8
3,153
2.546875
3
[]
no_license
#!/usr/bin/ruby -w require 'rubygems' require 'nokogiri' require 'sinatra' require 'yaml' require RUBY_VERSION < '1.9' ? 'fastercsv' : 'csv' CSV = FasterCSV if not defined? CSV require './anki_card_generator' require './esv_api_request' require './sentence_splitter' class AnkiVerse < Sinatra::Base SUGGESTED_PASSAGES = (<<-END).split(/\n/).map {|line| line.strip } Genesis 1 Genesis 12 Exodus 14 Exodus 20 Deuteronomy 6 2 Samuel 7 Psalm 1 Psalm 23 Psalm 96 Psalm 100 Psalm 121 Isaiah 6 Isaiah 40 Isaiah 53 Obadiah Malachi 4 Matthew 5 Matthew 6 Mark 1 Mark 15 Luke 2 Luke 24 John 1 John 20 Romans 1 Romans 3 Romans 8 1 Corinthians 13 1 Corinthians 15 Philippians 2 Jude Revelation 1 Revelation 21 Revelation 22 END get '/' do @passage = SUGGESTED_PASSAGES[rand(SUGGESTED_PASSAGES.size)] erb :index end post '/' do next params.to_yaml if params["debug"] response['Content-Type'] = "text/csv; charset=utf-8" response['Content-Disposition'] = "attachment; filename=ankiverse.csv" AnkiCardGenerator.new(params["poem"], params["other_fields"]). csv(:lines => params["lines"].map(&:to_i), :ellipsis => !!params["ellipsis"]) end get '/bible/:passage/:version/:verse_numbers?' do case params[:version] when 'NIV' body = Net::HTTP.get(URI.parse("https://www.biblegateway.com/passage/?version=NIV&search=" + params[:passage].gsub(/\s+/, '+'))) doc = Nokogiri(body.gsub(/\<br[^>]*?\>/, "\n")) passage = doc.css('.passage-text') passage.search('h1').remove passage.search('h3').remove passage.search('sup').remove unless params[:verse_numbers] == 'with_verse_numbers' passage.search('.chapternum').remove passage.search('.footnotes').remove passage.search('.crossrefs').remove passage.search('.publisher-info-bottom').remove ref = "#{params[:passage]} (NIV)" text = "#{ref}\n#{passage.text}\n#{ref}" when 'ESV' options = { :key => "IP", :output_format => "plain-text", :line_length => 0, :dont_include => %w( passage-references first-verse-numbers footnotes footnote-links headings subheadings audio-link short-copyright passage-horizontal-lines heading-horizontal-lines ) } options[:dont_include] << 'verse_numbers' unless params[:verse_numbers] == 'with_verse_numbers' response = EsvApiRequest.execute(:passageQuery, options.merge(:passage => params[:passage])) # Add whitespace to verse numbers if necessary for more readability response.gsub!("\]", "\] ") if params[:verse_numbers] == 'with_verse_numbers' text = "#{params[:passage]}\n#{response}" else raise ArgumentError, "Please select a valid version" end @passage = params[:passage] @poem = SentenceSplitter.new(text).lines_of(5..12).join("\n") @other_fields = [@passage] erb :index end end
true
bb2f8662ee16d7b30d110c153d815138e985adaf
Ruby
tomejesus/courier-kata
/app.rb
UTF-8
983
3.03125
3
[]
no_license
require './lib/controller.rb' class CourierBot < Controller def add_ten 3.times { new_parcel(9, 8, 7, 0.5) } 2.times { new_parcel(49, 38, 27, 5) } 2.times { new_parcel(99, 88, 77, 5) } 1.times { new_parcel(209, 108, 97, 5) } 1.times { new_parcel(9, 8, 7, 51) } 1.times { new_parcel(49, 38, 27, 201) } puts('10 Parcels added!') end def add_thirty 5.times { new_parcel(9, 8, 7, 0.5) } 5.times { new_parcel(49, 38, 27, 5) } 5.times { new_parcel(99, 88, 77, 5) } 5.times { new_parcel(209, 108, 97, 5) } 5.times { new_parcel(9, 8, 7, 51) } 5.times { new_parcel(49, 38, 27, 201) } puts('25 Parcels added!') end def add_fifty 15.times { new_parcel(9, 8, 7, 0.5) } 15.times { new_parcel(49, 38, 27, 5) } 5.times { new_parcel(99, 88, 77, 5) } 5.times { new_parcel(209, 108, 97, 5) } 5.times { new_parcel(9, 8, 7, 51) } 5.times { new_parcel(49, 38, 27, 201) } puts('50 Parcels added!') end end
true
a65826ce30c0d48262711f75f2401bd9449bfd93
Ruby
pocke/gry
/lib/gry/formatter.rb
UTF-8
1,266
2.703125
3
[ "Apache-2.0" ]
permissive
module Gry class Formatter def initialize(display_disabled_cops:) @display_disabled_cops = display_disabled_cops end # @param gry_result [Array<Law>] # @return [String] a yaml string def format(laws) confs = laws.map do |law| if law.letter letter = {law.name => law.letter} else if @display_disabled_cops letter = {law.name => {'Enabled' => false}} else next end end comment = RubocopAdapter.metrics_cop?(law.name) ? '' : to_comment(law.bill) yaml = to_yaml(letter) comment + yaml end.compact to_yaml(RubocopAdapter.config_base) + "\n" + confs.join("\n") end private def to_yaml(hash) YAML.dump(hash)[4..-1] end def to_comment(set_count) set_count.map do |setting, offenses| count = offenses.size x = setting .reject{|key, _| key == 'Enabled'} .map{|key, value| "#{key}: #{value}"} .join(', ') "# #{x} => #{count} #{offenses(count)}\n" end.join end def offenses(count) if count > 1 'offenses' else 'offense' end end end end
true
2805a0dba6d6adcd88974d6243a3e19ffeaa9b0e
Ruby
JakobErlandsson/AdventofCode
/2019/helper.rb
UTF-8
191
3.125
3
[]
no_license
def readFile(filename) lines = [] text=File.open(filename).read text.each_line do |line| line.gsub!(/(\n*)$/, '') lines.push(line) end return lines end
true
e9bb4cf9850066a34c436727590ff0bad90eb8ef
Ruby
d3slife/beginner_ruby_projects
/stock_picker.rb
UTF-8
479
4.03125
4
[]
no_license
def stock_picker(array) length = array.length odds = 0 buy_day = 0 sell_day = 0 length.times do |step| buy = array[step] (length - step - 1).times do |inner_step| sell = array[inner_step + step + 1] if (odds < sell - buy) odds = sell - buy buy_day = step sell_day = inner_step + step + 1 end end end puts "The best day for purchase is #{buy_day}. For selling - #{sell_day}" end stock_picker([17, 3, 6, 9, 15, 8, 6, 1, 10])
true
7d7dd5bb03fe041cbde569eca1a6769e9b43b0a5
Ruby
icecoll/leetcode
/remove-duplicates-from-sorted-list/app.rb
UTF-8
1,184
3.765625
4
[]
no_license
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} head # @return {ListNode} def delete_duplicates(head) list = SinglyLinkedList.new(head) list.remove_duplicates list.head end class SinglyLinkedList attr_accessor :head def initialize(head) @head = head end def remove_duplicates return nil if @head.nil? current_node = @head while current_node&.next current_node.remove_next_nodes while current_node.duplicate_with_next? current_node = current_node.next end end def to_array @head.list_values end def self.build(array) return nil if array.empty? array.reverse.reduce(nil) { |head, val| ListNode.new(val, head) } end end class ListNode attr_accessor :val, :next def initialize(val = 0, next_node = nil) @val = val @next = next_node end def list_values return [val] if @next.nil? [val, *@next.list_values] end def duplicate_with_next? @val == @next&.val end def remove_next_nodes @next = @next.next end end
true
c6e59fc8b20492497edb403897c743afee27b3da
Ruby
happyFish/tvdb
/lib/tvdb/client.rb
UTF-8
1,851
2.609375
3
[ "MIT" ]
permissive
module TVdb class Client attr_reader :api_key, :urls def initialize(api_key) @api_key = api_key @urls = Urls.new(api_key) end def search(name, options={}) default_options = {:lang => 'en', :match_mode => :all} options = default_options.merge(options) search_url = @urls[:get_series] % {:name => URI.escape(name), :language => options[:lang]} doc = Hpricot(OpenURI.open_uri(search_url).read) ids = if options[:match_mode] == :exact doc.search('series').select{|s| s.search('seriesname').inner_text == name }.collect{|e| e.search('id')}.map(&:inner_text) else doc.search('series').search('id').map(&:inner_text) end ids.map do |sid| get_series_from_zip(sid, options[:lang]) end.compact end def series_in_language(series, lang) return nil if !series.respond_to?(:tvdb_id) return series if lang == series.language get_series_from_zip(series.tvdb_id, lang) end def get_series_zip(id, lang='en') zip_file = open_or_rescue(@urls[:series_zip] % {:series_id => id, :language => lang}) zip_file.nil? ? nil : Zip::ZipFile.new(zip_file.path) end private def open_or_rescue(url) begin return OpenURI.open_uri(url) rescue OpenURI::HTTPError # 404 errors for some of the ids returned in search return nil end end def get_series_from_zip(sid, lang='en') zip = get_series_zip(sid, lang) return nil if zip.nil? xml = read_series_xml_from_zip(zip, lang) return xml ? Series.new(xml) : nil end def read_series_xml_from_zip(zip, lang='en') if entry = zip.find_entry("#{lang}.xml") entry.get_input_stream.read end end end end
true
9f0bd10e21fb6c7f4ee3599b7546debb6f6bf5db
Ruby
rubycdp/ferrum
/lib/ferrum/page/stream.rb
UTF-8
1,032
2.515625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Ferrum class Page module Stream STREAM_CHUNK = 128 * 1024 def stream_to(path:, encoding:, handle:) if path.nil? stream_to_memory(encoding: encoding, handle: handle) else stream_to_file(path: path, handle: handle) end end def stream_to_file(path:, handle:) File.open(path, "wb") { |f| stream(output: f, handle: handle) } true end def stream_to_memory(encoding:, handle:) data = String.new # Mutable string has << and compatible to File stream(output: data, handle: handle) encoding == :base64 ? Base64.encode64(data) : data end def stream(output:, handle:) loop do result = command("IO.read", handle: handle, size: STREAM_CHUNK) chunk = result.fetch("data") chunk = Base64.decode64(chunk) if result["base64Encoded"] output << chunk break if result["eof"] end end end end end
true
f9668da31c02da2383dbb8d75ad37f33c5f2b0d3
Ruby
queria/scripts
/update_repos.rb
UTF-8
4,865
2.6875
3
[]
no_license
#!/usr/bin/env ruby require 'yaml' require 'pathname' require 'fileutils' def help puts <<HELP $ update_repos.rb [path_to_config_file] Config file has to be YAML file with at least source_path, target_path and git_baseurl. If no path_to_config_file is specified, './update_repos.yml' placed next to this script will be used. * source_path: where to find repository names (like '/home/git/repos' if /home/git/repos/{project,books,kernel,etc}.git etc exists) * target_path: where to clone/update repositories (like '/home/redmine/external_repos') * git_baseurl: prefix for building repository urls (like 'git@github.com:' [including ending colon]) * ignore_repos: colon separated list of repository names to skip (from example above we could say 'books.git:etc.git') * run_after: string which will be executed after update (some shell commands etc, optional) so example config.yml could be: --- source_path: '/home/git/repositories' target_path: '/home/redmine/external_repos' git_baseurl: 'git@github.com:' ignore_repos: 'books.git:etc.git' run_after: 'wget -O /dev/null http://redmine.domain/sys/fetch_changesets?key=xyz' ... --------------------------------------------------------- Created at 10/2011 by Queria Sa-Tas <public@sa-tas.net> sa-tas.net || github.com/queria/ Published under FreeBSD License (use --license option) HELP end def license puts <<LICENSE Copyright 2011 Queria Sa-Tas. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Queria Sa-Tas ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Queria Sa-Tas OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. LICENSE end def find_repos(source_path, ignore_names) repos = [] to_scan = [source_path] while not to_scan.empty? scan_dir = to_scan.pop scan_dir.children.each do |child| next if not child.directory? if child.extname.eql? '.git' repo_name = child.to_s[source_path.to_s.length() + 1 .. -1] next if ignore_names.include? repo_name repos << repo_name else to_scan << child end end end return repos end def update_repo(repo_path, repo_name) Dir.chdir repo_path %x(git fetch origin +refs/heads/*:refs/heads/* 2>&1) puts "#{repo_name} update failed" unless $?.success? end def clone_repo(repo_path, repo_name, git_baseurl) if not repo_path.parent.exist? FileUtils.mkpath( repo_path.parent, :mode => 0700 ) end Dir.chdir repo_path.parent puts "New repository found: #{git_baseurl}#{repo_name}" %x(git clone --bare #{git_baseurl}#{repo_name} #{repo_path.basename} 2>&1) puts "#{repo_name} clone failed" unless $?.success? end def update_repos(git_baseurl, target_path, repos) repos.each do |repo_name| repo_path = (target_path + repo_name) if repo_path.directory? update_repo repo_path, repo_name else clone_repo repo_path, repo_name, git_baseurl end end end if ARGV.include? '--license' license exit 0 end config_path = Pathname.new('./update_repos.yml') config_path = Pathname.new(ARGV[0]) if ARGV[0] if config_path.relative? config_path = (Pathname($0).realpath().dirname() + config_path) end unless config_path.exist? puts '' puts " Missing path to config file: #{config_path}" help exit 1 end config = YAML::load_file(config_path) source_path = Pathname.new(config['source_path']) target_path = Pathname.new(config['target_path']) git_baseurl = config['git_baseurl'] ignore_names = config['ignore_names'].split(':') unless config['ignore_names'].nil? if source_path.nil? or not source_path.directory? \ or target_path.nil? or not target_path.directory? \ or git_baseurl.nil? puts '' puts ' Missing configuration options:' help exit 2 end update_repos( git_baseurl, target_path, find_repos(source_path, ignore_names)) if config['run_after'] `#{config['run_after']}` end
true
b970e7effbfed5cd9a1ef0def629a8e3516c93b7
Ruby
seanchavez/swe_foundations
/rspec_exercise_5/lib/exercise.rb
UTF-8
1,243
3.5625
4
[]
no_license
require_relative "../../rspec_exercise_4/lib/part_1.rb" def zip(*arrs) zipped = [] arrs.first.length.times do |i| zipped[i] = [] arrs.each {|arr| zipped[i] << arr[i]} end zipped end def prizz_proc(arr, prc_1, prc_2) xor_select(arr, prc_1, prc_2) end def zany_zip(*arrs) zipped = [] arrs.max {|a, b| a.length <=> b.length}.length.times do |i| zipped[i] = [] arrs.each {|arr| arr[i] ? zipped[i] << arr[i] : zipped[i] << nil} end zipped end def maximum(arr, &prc) arr.reduce {|largest, el| prc.call(largest) > prc.call(el) ? largest : el} end def my_group_by(arr, &prc) grouped = Hash.new {|h, k| h[k] = []} arr.each {|el| grouped[prc.call(el)] << el} grouped end def max_tie_breaker(arr, prc, &blk) arr.reduce do |lrg, el| case when blk.call(el) > blk.call(lrg) then el when blk.call(el) == blk.call(lrg) prc.call(el) > prc.call(lrg) ? el : lrg else lrg end end end def silly_syllables(sent) vowel_s = "aeiou" sent.split.map do |word| start_i = end_i = nil word.each_char.with_index do |char, i| if vowel_s.include?(char) start_i ? end_i = i : start_i = i end end end_i ? word[start_i..end_i] : word end.join(" ") end
true
cb1d1e35236ee24558de637c1c1474dcaec736cb
Ruby
javierhonduco/server_timing_middleware
/lib/server_timing_middleware.rb
UTF-8
1,574
2.65625
3
[ "MIT" ]
permissive
# This simple Rack middleware subscribes to all AS::Notifications # and adds the appropriate `Server-Timing` header as described in # the spec [1] with the notifications grouped by name and with the # elapsed time added up. # # [1] Server Timing spec: https://w3c.github.io/server-timing/ module Rack class ServerTimingMiddleware def initialize(app) @app = app end def call(env) events = [] subs = ActiveSupport::Notifications.subscribe(//) do |*args| events << ActiveSupport::Notifications::Event.new(*args) end status, headers, body = @app.call(env) # As the doc states, this harms the internal AS:Notifications # caches, but I'd say it's necessary so we don't leak memory ActiveSupport::Notifications.unsubscribe(subs) mapped_events = events.group_by { |el| el.name }.map{ |event_name, event_data| agg_time = event_data.map{ |ev| ev.duration }.inject(0){ |curr, accum| curr += accum} # We need the string formatter as the scientific notation # a.k.a <number>e[+-]<exponent> is not allowed # Time divided by 1000 as it's in milliseconds [event_name, '%.10f' % (agg_time/1000)] } # Example output: # 'cpu;dur=0.009;desc="CPU", mysql;dur=0.005;desc="MySQL", filesystem;dur=0.006;desc="Filesystem"' headers['Server-Timing'] = mapped_events.map do |name, elapsed_time| "#{name};dur=#{elapsed_time};desc=\"#{name}\"" end.join(',') [status, headers, body] end end end
true
c45b29c3eb839ec9bce4cb880edac941b6055e7e
Ruby
kolba8/Ruby-introduction
/ruby-introduction/multiplication.rb
UTF-8
274
3.21875
3
[]
no_license
#!/usr/bin/env ruby i = 1 j = 1 print " " while j <= 10 print "%-4d" % j j += 1 end puts j=1 print " " 10.times {print "___ "} puts while i <= 10 print "%-4d" % i, "| " while j <= 10 print "%-4d" % (j*i) j += 1 end i += 1 j = 1 puts end
true
a565a1ccb5fe36c33d45c338bda10f72308cb60f
Ruby
PacificRebel/supremebnb
/spec/booking_spec.rb
UTF-8
1,197
2.578125
3
[]
no_license
describe @booking do before :each do @space = Space.create( name: 'taj mahal', start_date: '2019-10-23', end_date: '2020-10-23', price: 100, description: 'cool') @user = User.create(username: 'name') @date = "2019-12-25" @booking = Booking.create(space_id: @space.id, guest_id: @user.id, date: @date) end it 'knows its @space_id' do expect(@booking.space_id).to eq @space.id end it 'knows its guest_id' do expect(@booking.guest_id).to eq @user.id end it 'knows its @booking @date' do expect(@booking.date).to eq Date.new(2019,12,25) end it 'knows its approval status' do expect(@booking.approved?).to be_falsey end describe 'approve!' do it 'approves the @booking' do expect(@booking.approved?).to be_falsey @booking.approved! expect(@booking.approved?).to be true end end describe '.booked?' do it 'returns false if no approved @bookings exist' do expect(Booking.booked?(@space.id, @date)).to eq false end it 'returns true if approved @bookings exist' do @booking.approved! expect(Booking.booked?(@space.id, @date)).to eq true end end end
true
9fd20936150262a5afdfad205ec2b11c7f21ed29
Ruby
atl15/CS169.1x
/HW01/lib/ruby_intro.rb
UTF-8
660
3.875
4
[]
no_license
# When done, submit this entire file to the autograder. # Part 1 def sum arr arr.inject(0, :+) end def max_2_sum arr arr.max(2).inject(0, :+) end def sum_to_n? arr, n arr.combination(2).any? { |a, b| a + b == n } end # Part 2 def hello(name) "Hello, #{name}" end def starts_with_consonant? s s =~ /^[^aeiou\d\W]/i end def binary_multiple_of_4? s s =~ /^(1|0)+$/ && s.to_i(2) % 4 == 0 end # Part 3 class BookInStock def initialize(isbn, price) raise ArgumentError if isbn.empty? || price <= 0 @isbn = isbn @price = price end attr_accessor :isbn, :price def price_as_string "$#{'%.2f' % self.price}" end end
true
88bf0df0d650f0e5806faa6b9ac2b990c20b3faf
Ruby
firehoseCheckmates/ourGame
/app/models/queen.rb
UTF-8
468
2.921875
3
[]
no_license
class Queen < Piece def legal_move?(row, col) #queen can move anywhere vacant self.legal_horiz_move?(row, col) || self.legal_vert_move?(row, col) || self.legal_diag_move?(row, col) end def piece_exists?(row, col) Piece.where(row_position: row, col_position: col).exists? end def obstructed_path?(row, col) end def valid_move?(row, col) end def piece_where_moving_to?(row, col) end def piece_still_on_board?(row, col) end end
true
57913af90dd0451914c21a429872fa2274753d9c
Ruby
msanroman/StringCalculator
/lib/String.rb
UTF-8
654
3.75
4
[]
no_license
require 'Delimiters' class String CUSTOM_DELIMITER_PREFIX = '//' CUSTOM_DELIMITER_SUFFIX = '\n' def split! delimiters = Delimiters.new(customDelimiter) regular_expression = Regexp.new(delimiters.to_s) self.split(regular_expression).collect { |number| number.to_i } end def hasCustomDelimiter? self.start_with?(CUSTOM_DELIMITER_PREFIX) end def customDelimiter return '' unless hasCustomDelimiter? self[custom_delimiter_start..custom_delimiter_end] end def custom_delimiter_start CUSTOM_DELIMITER_PREFIX.length end def custom_delimiter_end CUSTOM_DELIMITER_SUFFIX.length end end
true
ed2a91599c54af72aaae2864ceb84766a49afd73
Ruby
james1239090/mask_store
/app/models/purchase.rb
UTF-8
2,394
2.5625
3
[]
no_license
class Purchase < ApplicationRecord has_many :purchase_items, dependent: :destroy has_many :items, through: :purchase_items, source: :product validates :total_tw_price, :total_tw_duty ,:total_tw_service_fee, :total_currency_shipping_fee, :purchase_items, presence: true accepts_nested_attributes_for :purchase_items, reject_if: :all_blank, :allow_destroy => true monetize :total_tw_price, :as=> "total_tw_cents" , :with_currency => :twd def total_currency! sum = 0 purchase_items.each do |purchase_item| sum = sum + (purchase_item.currency_price * purchase_item.quantity) end self.total_currency_price = (sum + self.total_currency_shipping_fee).round(2) self.save end def calculate_currency_rate! rate = self.total_tw_price / self.total_currency_price self.currency_rate = rate.round(4) self.save end def calculate_each_tw_price! purchase_items.each do |purchase_item| purchase_item.tw_price = (purchase_item.currency_price * self.currency_rate).round(2) purchase_item.save end end def calculate_tw_total_shipping_fee! self.total_tw_shipping_fee = (self.total_currency_shipping_fee * self.currency_rate).round(2) self.save end def calculate_each_fee! total_currency = self.total_currency_price - self.total_currency_shipping_fee duty = self.total_tw_duty tw_shipping = self.total_tw_shipping_fee service_fee = self.total_tw_service_fee purchase_items.each do |purchase_item| purchase_item.duty = ((purchase_item.currency_price * duty) / total_currency).round(2) purchase_item.shipping_fee = ((purchase_item.currency_price * tw_shipping) / total_currency).round(2) purchase_item.service_fee = (purchase_item.currency_price * service_fee / total_currency).round(2) purchase_item.sub_total = purchase_item.tw_price + purchase_item.duty + purchase_item.shipping_fee + purchase_item.service_fee purchase_item.total = (purchase_item.sub_total * purchase_item.quantity).round(2) purchase_item.sub_total = purchase_item.sub_total.round(2) purchase_item.save end end def caculate_round_diff! total = 0 purchase_items.each do |purchase_item| total = total + purchase_item.total end self.round_diff_money = self.total_tw_price + self.total_tw_duty + self.total_tw_service_fee - total self.save end end
true
13a0bb8e69921693b1a8a9ce1d0d8b5f4bb270bf
Ruby
eugene-utkin/ruby_school_lesson_05
/app10.rb
WINDOWS-1251
611
3.0625
3
[]
no_license
# encoding: cp1251 if (Gem.win_platform?) Encoding.default_external = Encoding.find(Encoding.locale_charmap) Encoding.default_internal = __ENCODING__ [STDIN, STDOUT].each do |io| io.set_encoding(Encoding.default_external, Encoding.default_internal) end end arr = %w[ ] while true x = 1 arr.each do |name| puts "#{x} - #{name}" x = x + 1 end puts " , ." n = gets.to_i print n arr.delete_at n-1 puts " : " puts arr end
true
2c3787fb991e3d1ef54d630f6cf6dbdda21f1438
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex1142.rb
UTF-8
522
3.578125
4
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 539 class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello
true
cbfc284fa7842338ea9208e04965fb0b43a9b57d
Ruby
michaeleconomy/town_generator
/lib/town_generator/model/person/health.rb
UTF-8
540
2.578125
3
[]
no_license
class TownGenerator::Person < TownGenerator::Model def cause_of_death self[:cause_of_death] end def dead? self[:died_at] <= TownGenerator::Date.current end def alive? born? && !dead? end def born? birthday >= TownGenerator::Date.current end def die(date, cause) self[:died_at] = date self[:cause_of_death] = cause end_marriage move_out leave_job #TODO - remove any illnesses delete(:pregnant) town.residents.delete(:self) town.deceased << self end end
true
365c0b317f47e37ac2f8ee00546abb5cf7e08757
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/difference-of-squares/4c95a60c29a34e31af65ec2969172a57.rb
UTF-8
421
3.65625
4
[]
no_license
class Squares def initialize(num) @num = num end def square_of_sums square(sum) end def sum_of_squares sum(square) end def difference square_of_sums - sum_of_squares end private def square(values = (1..@num)) if values.is_a? Range values.map { |num| num ** 2 } else values ** 2 end end def sum(values = (1..@num)) values.inject(0, &:+) end end
true
46c64b8fde7a061b1dbb419611eea80cf198b05a
Ruby
EthanStein/Movies2
/movies_part2.rb
UTF-8
2,730
3.09375
3
[]
no_license
class MovieData attr_reader :u, :m, :k def initialize(u, m, k, movie_data) @u = Hash.new @m = Hash.new @k = Hash.new @movie_data = [] end def load_data() prompt = '> ' puts "Hi! Which file would you like to open?", prompt #We prompted the user to give us what file to open and called it file_name file_name = $stdin.gets.chomp #making a "file object file = open(file_name) #create a block that takes a parameter file.each do|line| # #splits the line at tab character into row Array #http://stackoverflow.com/questions/20807484/why-is-my-ruby-script-not-splitting-the-field-in-my-csv single_line = line.chomp.split("\t") #line_info is an hash with each of the four piece of information in each line from file line_info = {'user_id' => single_line[0], 'movie_id' => single_line[1], 'rating' => single_line[2], 'timestamp' => single_line[3]} @movie_data.push(line_info) end #returns the rating that user u gave movie m in the training set, and 0 if user u did not rate movie m' def rating(file, u,m) =begin file.each do |movie, rating| if rating == 0 return file[movie], "0" else return file[movie], file[rating] end end end =end @u[user_id].rating(movie_id) def predict(u,m) return @u[user_id].average #returns a floating point number between 1.0 and 5.0 as an estimate of what user u would rate movie m' end #returns the array of movies that user u has watched def movies(file, u) return @u[user_id].user_id.movie_id end #returns the array of users that have seen movie m def viewers(file,m) return @m[movie_id].user_id.rating end def run_test(k) puts runs the z.predict method on the first k ratings in the test set and return MovieTest end end class MovieTest attr_reader :u, :m, :k def initialize(u, m, k, movie_data) @u = u @m = m @k = k @movie_data = [] end def mean (array) #To calculate the standard deviation we work out the mean. array.inject(array.inject(0)) {|sum, z| sum = sum + z } / array.size.to_f end def squared_differences #We work out the mean of those squared differences #For each number subtract the Mean and square the result. x = array.mean sum = array.inject(0){|x, mean| (x-mean)*(x-mean)} sum/(array.length -1).to_f end end def stddev #Take the square root of that. return Math.sqrt(array.squared_differences) end def rms (z.predict) Math.sqrt(z.predict) end def to_a prediction_array = [u, m, r, p] return prediction_array end z = MovieData.new("ml-100k") z = MovieTest.new("ml-100k")
true
b591efb3ac681f6240628c478452bac488e3f9d3
Ruby
TStrothjohann/rps-challenge
/features/step_definitions/rps_steps.rb
UTF-8
1,226
2.890625
3
[]
no_license
Given(/^I am on the homepage$/) do visit '/' end When(/^I enter my name$/) do fill_in('playername', :with=>'Thomas') end When(/^click on "(.*?)"$/) do |arg1| click_button('Start Game') end Then(/^I will see three options "(.*?)", "(.*?)", "(.*?)"$/) do |arg1, arg2, arg3| expect(page).to have_content(arg1) expect(page).to have_content(arg2) expect(page).to have_content(arg3) end #________________ Given(/^I have registered and see the options$/) do visit('/register') fill_in('playername', :with=>'Thomas') click_button('Start Game') find('form#rps') end When(/^I choose a weapon$/) do choose('weapon_1') click_button('Choose') end Then(/^I should see my score$/) do expect(page).to have_content("Your count:") end #________________ Given(/^the players have taken three turns each$/) do visit('/register') fill_in('playername', :with=>'Thomas') click_button('Start Game') find('form#rps') choose('weapon_1') click_button('Choose') find('form#rps') choose('weapon_1') click_button('Choose') find('form#rps') choose('weapon_1') click_button('Choose') end Then(/^he should know that he is the winner$/) do expect(page).to have_content("Thomas has won") end
true
77e334c944658bc5574b8eed747c73660d4253f9
Ruby
andyprickett/launch-school
/exercises/100-ruby-basics/06-user-input/10_opposites_attract.rb
UTF-8
665
3.96875
4
[]
no_license
def valid_number?(number_string) number_string.to_i.to_s == number_string && number_string.to_i != 0 end def get_validated_input input = nil loop do puts ">> Please enter a positive or negative integer:" input = gets.chomp if !valid_number?(input) puts ">> Invalid input. Only non-zero integers are allowed." else break end end input.to_i end int1, int2 = nil loop do int1 = get_validated_input int2 = get_validated_input break if (int1 * int2) < 0 puts ">> Sorry. One integer must be positive, one must be negative." puts ">> Please start over." end sum = int1 + int2 puts ">> #{int1} + #{int2} = #{sum}"
true
1eb69ff455c81630f8921d8ea6c5a6e9771791fe
Ruby
schenkc/commutator
/not_factorable.rb
UTF-8
588
2.859375
3
[]
no_license
require './word_processing' #This should write elements of F' that are not yet factored in a file commutators = File.open("6disk_commutators.csv", "r") elements = File.open("commutators_in_16disk.txt", "r") result = File.open("in_16_notin6.txt" , "w+") counter_ex_hash =Hash.new elements.each do |line| counter_ex_hash[line] = true end commutators.each do |line| a = line.split(',') a[0]=a[0].chomp! counter_ex_hash.delete_if{|key, value| key == a[0] } end if counter_ex_hash.nil? result.puts "everything factors" end counter_ex_hash.each_key {|key| results.puts key }
true
77e0855af370ba8f2b83618e54c2ed60e93fe7ba
Ruby
BrandonTat/Practice-Problems
/leetcode/problems/evaluate_rpn.rb
UTF-8
903
4.15625
4
[]
no_license
# Evaluate the value of an arithmetic expression in Reverse Polish Notation. # # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # # Some examples: # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 # param {String[]} tokens # return {Integer} def eval_rpn(tokens) values = [] tokens.each do |token| if token == "+" v1 = values.pop v2 = values.pop values << (v2 + v1) elsif token == "-" v1 = values.pop v2 = values.pop values << (v2 - v1) elsif token == "*" v1 = values.pop v2 = values.pop values << (v2 * v1) elsif token == "/" v1 = values.pop v2 = values.pop values << (v2.fdiv(v1).truncate) else values << token.to_i end end values.last end # Time Complexity - O(n) # Space Complexity - O(n)
true
c3fd985c1d731366807649733d1af80c75f5ec48
Ruby
Jpxg/Rubyd1
/exo_09.rb
UTF-8
148
3.234375
3
[]
no_license
puts "Quel est ton prenom?" user_name = gets.chomp puts "Quel est ton nom?" user_surname = gets.chomp puts "Bonjour, #{user_name} #{user_surname} !"
true
c378c2bf21cbfe0bf0eb13299ddc8284b895f995
Ruby
zachlatta/turntabler
/examples/switch.rb
UTF-8
1,054
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # On/Off bot switch require 'turntabler' EMAIL = ENV['EMAIL'] # 'xxxxx@xxxxx.com' PASSWORD = ENV['PASSWORD'] # 'xxxxx' ROOM = ENV['ROOM'] # 'xxxxxxxxxxxxxxxxxxxxxxxx' # Bot is on by default is_on = true TT.run(EMAIL, PASSWORD, :room => ROOM) do on :user_spoke do |message| if is_on # The bot is on case message.content when /^\/status$/ room.say 'The bot is currently turned on.' when /^\/off$/ room.say 'The bot is now turned off.' is_on = false when /^\/hello$/ # Add other logic here for when the bot is turned on. For example: # Respond to "/hello" command room.say "Hey! How are you #{message.sender.name}?" end else # The bot is off case message.content when /^\/status$/ room.say 'The bot is currently turned off.' when /^\/on$/ room.say 'The bot is now turned on.' is_on = true end # Add other logic here for when the bot is turned off end end end
true
f03f5dcb771e7709ed0002814f96e93e7cf3b116
Ruby
hathach/tinyusb
/test/unit-test/vendor/ceedling/lib/ceedling/system_utils.rb
UTF-8
685
2.84375
3
[ "MIT" ]
permissive
class Object def deep_clone Marshal::load(Marshal.dump(self)) end end ## # Class containing system utility functions. class SystemUtils constructor :system_wrapper ## # Sets up the class. def setup @tcsh_shell = nil end ## # Checks the system shell to see if it a tcsh shell. def tcsh_shell? # once run a single time, return state determined at that execution return @tcsh_shell if not @tcsh_shell.nil? result = @system_wrapper.shell_backticks('echo $version') if ((result[:exit_code] == 0) and (result[:output].strip =~ /^tcsh/)) @tcsh_shell = true else @tcsh_shell = false end return @tcsh_shell end end
true
25baf53c6c8af93e797650d118b794269351cd0d
Ruby
srosso6/universe-game
/specs/universe_spec.rb
UTF-8
1,587
3.171875
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../map.rb") require_relative("../spaceship.rb") require_relative("../planet.rb") require_relative("../universe.rb") class TestUniverse < Minitest::Test def setup @LV426 = Planet.new("LV426", 10) @ice_pop = Planet.new("ice pop", 20) @new_wave = Planet.new("new wave", 20) @big_fizz = Planet.new("big fizz", 50) positions = { 0 => {planet: @ice_pop}, 1 => {wormhole: 15}, 2 => {planet: @LV426}, 6 => {planet: @new_wave}, 18 => {planet: @big_fizz} } @map = Map.new( 20, positions) @firefly = Spaceship.new( name: "Firefly", position: 2, fuel_level: 50, fuel_per_lightyear: 10 ) @waspy = Spaceship.new( name: "Waspy", position: 6, fuel_level: 40, fuel_per_lightyear: 5 ) @bf_rescue = Spaceship.new( name: "big_fizz_rescue", position: 18, fuel_level: 100, fuel_per_lightyear: 1) @spaceships = [@firefly, @waspy, @bf_rescue] @universe = Universe.new(@map, @spaceships) end def test_refuel_if_planet @firefly.move(4) @universe.refuel_on_planet() assert_equal(50, @firefly.fuel_level) end def test_not_refuel_if_not_planet @firefly.move(3) @universe.refuel_on_planet() assert_equal(20, @firefly.fuel_level) end def test_move_if_wormhole @firefly.move(-1) @universe.move_through_wormhole() assert_equal(16, @firefly.position) assert_equal(40, @firefly.fuel_level) end def test_transfer_fuel() @universe.transfer_fuel() assert_equal(20, @firefly.fuel_level) end end
true
7cd9a6c213afca00d58abbb48893353e330a6297
Ruby
gulcebasar/cs342-Design-Patterns
/project1/Axe.rb
UTF-8
124
2.578125
3
[]
no_license
require_relative 'Weapon' class Axe < Weapon def initialize() super( 2, "axe") #Axes strength is 2 end end
true
554fef2a6384e2806b8e606cdf2c528472f23cbb
Ruby
glassjoseph/black_thursday
/lib/invoice.rb
UTF-8
924
2.65625
3
[]
no_license
require_relative "../lib/data_access" class Invoice include DataAccess def merchant parent.parent.merchants.find_by_id(merchant_id) end def invoice_items parent.parent.invoice_items.find_all_by_invoice_id(id) end def items item_ids = invoice_items.map { |invoice_item| invoice_item.item_id } item_ids.map {|item_id| self.parent.parent.items.find_by_id(item_id) } end def transactions parent.parent.transactions.find_all_by_invoice_id(id) end def customer parent.parent.customers.find_by_id(customer_id) end def is_paid_in_full? invoice_transactions = parent.parent.transactions.find_all_by_invoice_id(id) return false if transactions.empty? invoice_transactions.any? {|transaction| transaction.result == "success"} end def total return 0.0 unless is_paid_in_full? invoice_items.inject(0){ |sum, ii| sum + ii.unit_price * ii.quantity } end end
true
cf381b2df11d4dc7e22fd04ea9030e6a9fc41534
Ruby
dmleach/advent-of-code-2019
/solver/Solver03.rb
UTF-8
5,641
3.265625
3
[]
no_license
require __dir__ + "/BaseSolver" class WireSegment def initialize currentPosition, description @startPosition = currentPosition @direction = description[0] @length = description[1, description.length].to_i end def column if orientation == "V" return @startPosition[0] end raise RuntimeError "Vertical wires don't have a column value" end def direction return @direction end def endPosition _startColumn = @startPosition[0] _startRow = @startPosition[1] case @direction when "D" return [_startColumn, _startRow - @length] when "L" return [_startColumn - @length, _startRow] when "R" return [_startColumn + @length, _startRow] when "U" return [_startColumn, _startRow + @length] else raise ArgumentError, "Invalid direction: " + @direction end end def getIntersection segment if orientation == segment.orientation return nil end if orientation == "H" if (segment.range[0] <= row) && (segment.range[1] >= row) && (range[0] <= segment.column) && (range[1] >= segment.column) return [segment.column, row] end elsif orientation == "V" if (segment.range[0] <= column) && (segment.range[1] >= column) && (range[0] <= segment.row) && (range[1] >= segment.row) return [column, segment.row] end else raise ArgumentError, "Invalid orientation: " + orientation end return nil end def length return @length end def orientation case @direction when "D", "U" return "V" when "L", "R" return "H" end raise ArgumentError, "Invalid direction: " + @direction end def range if orientation == "H" return [@startPosition[0], endPosition[0]].sort elsif orientation == "V" return [@startPosition[1], endPosition[1]].sort end raise ArgumentError, "Invalid orientation: " + orientation end def row if orientation == "H" return @startPosition[1] end raise RuntimeError "Horizontal wires don't have a row value" end def to_s @startPosition.to_s + " to " + endPosition.to_s end end class Solver03 < BaseSolver @segments def displaySolution mode _closestIntersectionToOrigin = nil _closestIntersectionDistance = 9999999999 _shortestCircuitLength = 999999999 _wire1Length = 1 @segments[0].each do |_segment| _wire1Length = _wire1Length + _segment.length - 1 end _wire2Length = 1 @segments[1].each do |_segment| _wire2Length += _wire2Length + _segment.length - 1 end _wire1LengthToStart = 1 @segments[0].each_with_index do |_segment1, _idxSegment1| _wire1LengthToStart += _segment1.length - 1 _wire2LengthToStart = 1 @segments[1].each_with_index do |_segment2, _idxSegment2| _wire2LengthToStart += _segment2.length - 1 if _segment1.orientation == _segment2.orientation next end _intersection = _segment1.getIntersection _segment2 if _intersection == nil next end if _intersection[0] == 0 and _intersection[1] == 0 next end if mode == 1 if _intersection[0].abs + _intersection[1].abs < _closestIntersectionDistance _closestIntersectionToOrigin = _intersection _closestIntersectionDistance = _intersection[0].abs + _intersection[1].abs end end if mode == 2 _wire1LengthToOrigin = _wire1LengthToStart if _wire1Length - _wire1LengthToStart < _wire1LengthToOrigin _wire1LengthToOrigin = _wire1Length - _wire1LengthToStart end _wire2LengthToOrigin = _wire2LengthToStart if _wire2Length - _wire2LengthToStart < _wire2LengthToOrigin _wire2LengthToOrigin = _wire2Length - _wire2LengthToStart end if _wire1LengthToOrigin + _wire2LengthToOrigin < _shortestCircuitLength _shortestCircuitLength = _wire1LengthToOrigin + _wire2LengthToOrigin end end end end if mode == 1 puts "The closest intersection to the origin is " + _closestIntersectionDistance.to_s + " away at " + _closestIntersectionToOrigin.to_s end if mode == 2 puts "The shortest circult length is " + _shortestCircuitLength.to_s end end def initializeSolution @segments = Array.new end def processInput input, mode _segments = Array.new _inputValues = input.split(",") _currentPosition = [0,0] _inputValues.each do |_inputValue| _segment = WireSegment.new(_currentPosition, _inputValue) _currentPosition = _segment.endPosition _segments << _segment end @segments << _segments end end
true
598aa6bc010e05a9515923fc6dc03f57166337dd
Ruby
jonisavo/MK-Starter-Kit
/ruby/scripts/tempdebug/tileset6.rb
UTF-8
865
2.71875
3
[]
no_license
# Creates a new tileset (normally loaded from a file) tileset = MKD::Tileset.new(6) tileset.name = "Fences & Rails" tileset.graphic_name = "fences_and_rails" # 0 = impassable # 1 = passable down # 2 = passable left # 4 = passable right # 8 = passable up # 11 = passable down, left, up # etc. # 15 = passable all tileset.passabilities = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 0, 15, 0, 0, 0, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 15, 0, 15, 0, 0, 0, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 15, ] tileset.priorities = [] tileset.tags = [] tileset.save
true
4e1d31e0a45d81d2815a7772ef27b56d6159c978
Ruby
DILLONDNGUYEN/cli_charities
/lib/cli_charities/cli.rb
UTF-8
1,969
3.28125
3
[ "MIT" ]
permissive
class CLI def start puts "Hello, Welcome to Charities CLI".colorize(:green) puts location #greetings and direction end def get_input input = gets.strip.downcase if input =="exit" puts "Goodbye".colorize(:red) exit elsif input == "back" self.location end return input.to_i end def get_charities(input) API.get_charities(input) #instantiate objects in the api class method end def display_charities #binding.pry Charity.all.each.with_index(1) do |c,index| puts "#{index} - #{c.name}".colorize(:cyan) end end def location puts "Please enter a Zip Code or exit".colorize(:magenta) input = get_input input_validation(input) Charity.all.clear get_charities(input) #binding.pry display_charities self.org end def org puts "Select Organization by Number, Enter back to enter a new Zipcode, or exit to exit".colorize(:magenta) #ability to select organization to view url index = get_input - 1 if !index.between?(1, Charity.all.length - 1) #OR (1..Charity.all.length).include?(index) #binding.pry display_charities puts "Please try again".colorize(:red) sleep(1) else #(!Charity.all[index].nil?) puts Charity.all[index ].name.colorize(:green) puts Charity.all[index ].city.colorize(:green) puts Charity.all[index ].state.colorize(:green) puts Charity.all[index ].url.colorize(:blue) puts Charity.all[index ].missionStatement puts Charity.all[index ].category.colorize(:green) end self.org end def input_validation (input) if input.to_s.length != 5 && "abcdefghijklmnopqrstuvwxyz".split('').any? puts "Please enter a valid Zip Code".colorize(:red) self.location end end end #end
true
94caa377741e8d84e6d2ee369629a5f7fb569432
Ruby
codeshowcase-pv/tictactoe
/exceptions/invalid_input.rb
UTF-8
314
2.625
3
[]
no_license
# frozen_string_literal: true class InvalidInput < StandardError attr_reader :input def initialize(input) @input = input super(message) end def message "Некоррекнтый ввод. Вы ввели #{input}. Допустимы только координаты клеток" end end
true
7c4736bb89bb53f790d50acb144a7b64c35db7ed
Ruby
mdellandrea/ruby_benchmarks
/block_vs_proc_memory_allocation.rb
UTF-8
613
3.421875
3
[]
no_license
# Memory allocation costs of creating a closure def block_call &block block.call end def just_yield yield end GC.disable y = GC.stat[:malloc_increase_bytes] block_call { 1 + 1 } z = GC.stat[:malloc_increase_bytes] GC.enable memory_change_1 = z-y #================================================================================================== GC.disable y = GC.stat[:malloc_increase_bytes] just_yield { 1 + 1 } z = GC.stat[:malloc_increase_bytes] GC.enable memory_change_2 = z-y puts "creating a closure allocated an additonal #{ memory_change_1 - memory_change_2 } bytes of RAM"
true
e1e3dae90515fb5e853cbdc003129e647b39590f
Ruby
execb5/.vim
/aux_scripts/merge_chapters.rb
UTF-8
1,345
2.703125
3
[]
no_license
#! /usr/bin/env ruby # frozen_string_literal: true require 'fileutils' require 'optparse' command = ARGV.shift case command when '-s' folder_name = ARGV.shift Dir.mkdir(folder_name) unless File.exist?(folder_name) ARGV.sort.each do |chapter| Dir.glob("#{chapter}/*").sort.each_with_index do |file, i| extension = File.extname(file) file_name = format("#{folder_name}/#{chapter}-%02d#{extension}", i) FileUtils.cp(file, file_name) end end when '-a' folder_name = ARGV.shift Dir.mkdir(folder_name) unless File.exist?(folder_name) ARGV.sort.each do |volume| volume_folder = "#{folder_name}/#{volume}" FileUtils.mkdir_p(volume_folder) Dir.glob("#{volume}/**").sort.each do |chapter| Dir.glob("#{chapter}/*").each_with_index do |file, i| extension = File.extname(file) file_name = format("#{folder_name}/#{chapter}-%02d#{extension}", i) FileUtils.cp(file, file_name) end end cbz_name = "#{volume_folder}.cbz" system("zip -r \"#{cbz_name}\" \"#{volume_folder}\"") puts "#{cbz_name} produced!" FileUtils.remove_dir(volume_folder) end when '-z' ARGV.sort.each do |volume| cbz_name = "#{volume}.cbz" system("zip -r \"#{cbz_name}\" \"#{volume}\"") puts "#{cbz_name} produced!" end else puts 'No command was passed.' end
true
88be2fc8394eeeaabaeb35caa999b49f70520b87
Ruby
marklombardinelson/katas
/Strings/stop_gninnips_my_sdrow.rb
UTF-8
1,713
4.3125
4
[]
no_license
# See more at - https://medium.com/@lombardinelson/basic-kata-stop-gninnips-my-sdrow-9c5e6c8c55d7 # Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. # Examples: # spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" # spinWords( "This is a test") => returns "This is a test" # spinWords( "This is another test" )=> returns "This is rehtona test" def spinWords(string) string.split.map { |word| word.length >= 5 ? word.reverse : word }.join(" ") end # Thinking Exercise # # Read The Kata Before Starting # The outcome will return the same input or string the function # passed with the exception of spinning (.reverse) any word with # more than or equal to 5 letters. # To start I'll need to identify the words in the array (.split) # Identify the characters in each word in the array (.length) # When the chracters are >= 5 spin them (.reverse) # Return the new array in the same format (.join or .map) # # Use an example to test in irb # Test.assert_equals(spinWords("Hey fellow warriors"), # "Hey wollef sroirraw"); # # WHEN TEST FAILS # Try rearranging the code in different variations to see if it # was a formatting issue # # WHEN TEST CONTINUES TO FAIL # Dive in and read error results # # WHEN TEST CONTINUES TO FAIL # Google # How to reverse specific strings in and array ruby? # Selected Sources: Stack Overflow: Reverse a string in Ruby # And Reversing a Ruby String, without .reverse method # STILL FAILING - PEER_REVIEW # # Confirm Results and Attempt #
true
535dce5119a47261a19f19ca833ceb9c599806c9
Ruby
Jorge-Gingsberg/parrot-ruby-ruby-apply-000
/parrot.rb
UTF-8
65
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def parrot(squawk = "Squawk!") puts squawk return squawk end
true
069f77dcd8bfa6124aee322d8981331339644460
Ruby
haroldcampbell/angularjs-styleguide-explorer
/style-guide/extract-headings.rb
UTF-8
1,142
3.234375
3
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
require 'json' require './core' # def extract_headings(in_file) found_toc = false parser = Parser::Parser.new File.open(in_file).each_line do |line| if (line.match(/1\. \[/)) found_toc = true elsif found_toc parser.select_processor(line) parser.parse(line) end end parser.to_data end if (ARGV.length == 0) puts "Nothing to do." puts "USAGE: ruby extract-headings.rb Readme.md [output.json] [show_json]" puts "\tItems in the '[]' are optional, but must be used in the order listed if used at all." exit(); end puts "Processing '#{ARGV.first}' file." table_of_contents_array = extract_headings(ARGV.first) if (ARGV.length == 1 && ARGV == "show_json") puts "Showing the first two sections of the guide:" trimmed_results = table_of_contents_array[0, 2] puts JSON.pretty_generate(trimmed_results) exit() end if (ARGV.length == 2) File.open(ARGV[1], 'w') do |f| f.puts JSON.pretty_generate(table_of_contents_array) end puts "Written output to '#{ARGV[1]}'." exit() end if (ARGV.length == 3 && ARGV[2]=='show_json') puts JSON.pretty_generate(table_of_contents_array) end
true
e02791163541d71c320742a472a4019305d27a7f
Ruby
badlychadly/ttt-with-ai-project-v-000
/lib/players/computer.rb
UTF-8
488
3.203125
3
[]
no_license
require 'pry' module Players class Computer < Player def move(board) if !board.taken?("5") "5" elsif corners(board) corners(board) else board.cells.collect.with_index do |v,i| (i+1).to_s if v == " " end.compact.sample end end def corners(board) board.cells.collect.with_index(1){|v, i| i if v == " "}.compact.select do |n| n == 1 || n == 3 || n == 7 || n == 9 end.sample end end end
true
047609a334cc4233e5133c63809f0920f5f1bcdb
Ruby
biagioo/fd_schedule
/lib/fd_schedule/events.rb
UTF-8
602
3.09375
3
[ "MIT" ]
permissive
class Events attr_accessor :name, :date, :league, :location, :details @@all = [] def initialize(event_hash) event_hash.each{ |key, value| self.send("#{key}=",value)} @@all << self end # def initialize(name, date, league, location, details) # @name = name # self.send("name=",name) # @date = date # @league = league # @location = location # @details = details # @@all << self # end def self.all @@all end def self.create_events(events_array) events_array.each do |event_hash| Events.new(event_hash) end end end
true
e20ee187a216be4429f1d3741c6172e8fde6eebb
Ruby
missamynicholson/takeaway-challenge
/lib/order.rb
UTF-8
771
3.203125
3
[]
no_license
require_relative 'order_calculator' require_relative 'message_system' class Order def initialize(menu:, order_calculator:, message_system:) @dishes_ordered = [] @order_calculator = order_calculator @message_system = message_system @menu = menu end def add(dish, quantity) fail "Not on menu" unless on_menu?(dish) @dishes_ordered << {dish: dish, quantity: quantity} end def check_total(total) err = "Unverified order: total does not match order sum. Change payment." fail err unless verified?(total) send_msg end private def send_msg @message_system.send end def verified?(total) @order_calculator.verified?(total, @dishes_ordered) end def on_menu?(dish) @menu.include_dish?(dish) end end
true
ca9a72c431ce5877a73cb1398c22fa290d974991
Ruby
hackings/game_of_life
/lib/game_of_life.rb
UTF-8
2,025
3.28125
3
[]
no_license
class GameOfLife attr_accessor :x, :y, :cells, :errors, :interact_rules def initialize(x, y) @x = x @y = y @cells = Array.new(x){ Array.new(y, nil) } @errors = [] @interact_rules = [] end def add_rule(rule) interact_rules << rule end def add_cell(x, y, cell) cells[x][y] = cell end def valid? validate_cells errors.empty? end def play set_cell_neighbours_count self.cells = self.cells.map{ | arr_cells | arr_cells.map { |c| apply_interact_rules(c) } } end def display x.times{ |x_cord| puts cells[x_cord].collect(&:label).join(" ") } end private def validate_cells errors.push "all positions are not filled." if cells.flatten.any?(&:nil?) end def set_cell_neighbours_count raise errors.join(',') if !valid? x.times do |x_cord| y.times do |y_cord| #horizontal neighbours cells[x_cord][y_cord].count_neighbour(cells[x_cord][y_cord - 1].alive?) if y_cord > 0 cells[x_cord][y_cord].count_neighbour(cells[x_cord][y_cord + 1].alive?) if y_cord < y - 1 #vertical neighbour cells[x_cord][y_cord].count_neighbour(cells[x_cord - 1][y_cord].alive?) if x_cord > 0 cells[x_cord][y_cord].count_neighbour(cells[x_cord + 1][y_cord].alive?) if x_cord < x - 1 #left diagonal neighbours cells[x_cord][y_cord].count_neighbour(cells[x_cord - 1][y_cord - 1].alive?) if x_cord > 0 && y_cord > 0 cells[x_cord][y_cord].count_neighbour(cells[x_cord + 1][y_cord - 1].alive?) if x_cord < x - 1 && y_cord > 0 #right diagonal neighbours cells[x_cord][y_cord].count_neighbour(cells[x_cord - 1][y_cord + 1].alive?) if x_cord > 0 && y_cord < y - 1 cells[x_cord][y_cord].count_neighbour(cells[x_cord + 1][y_cord + 1].alive?) if x_cord < x - 1 && y_cord < y - 1 end end end def apply_interact_rules(cell) interact_rules.each do |rule| cell = rule.apply(cell) end cell end end
true
140558c72fe83d293d40cef16006451bdca7b735
Ruby
bizzylizzy04/codecademy-ruby
/Ruby/rating_movies.rb
UTF-8
801
3.15625
3
[]
no_license
movies = { the_notebook: 4, } puts "What would you like to do?" choice = gets.chomp case choice when "add" puts "What's your favorite movie?" title = gets.chomp if movies[title.to_sym].nil? puts "What would you rate it?" rating = gets.chomp movies[title.to_sym] = rating.to_i puts "The movie #{title} was added with a rating of #{rating}." else puts "That movie already exists! Its rating is #{movies[title.to_sym]}." end when "update" puts "What is your next favorite movie?" title = gets.chomp if movies[title.to_sym].nil? puts "That movie already exists! Its ratingis #{movies[title.to_sym]}." else puts "What would you rate it?" end when "display" movies.each do |movie, rating| puts "#{movie}: #{rating} end else puts "Error!" end
true
e61c1645c16890338983371b8219deb8b8f12633
Ruby
xis19/leetcode
/680.rb
UTF-8
228
3.640625
4
[]
no_license
def valid_palindrome(s) def valid(s) s.nil? || s.reverse == s end i = 0 j = s.length - 1 while i < j return valid(s[i + 1..j]) || valid(s[i..j-1]) if s[i] != s[j] i += 1 j -= 1 end return true end
true
2e0435752a77027f5323fb16a711c32becb318a3
Ruby
seoulstice/battleship
/test/player_test.rb
UTF-8
2,406
3
3
[]
no_license
require 'minitest/autorun' require './lib/player' require 'pry' class PlayerTest < Minitest::Test def test_player_exists player = Player.new assert_instance_of Player, player end def test_player_has_a_board player = Player.new assert_instance_of Board, player.board end def test_player_has_empty_destroyer_by_default player = Player.new assert_equal [], player.destroyer assert_equal 0, player.destroyer.length end def test_player_has_empty_battleship_by_default player = Player.new assert_equal [], player.battleship assert_equal 0, player.battleship.length end def test_player_has_empty_destroyer1_string player = Player.new assert_equal "", player.destroyer1 end def test_player_has_empty_battleship1_string player = Player.new assert_equal "", player.battleship1 end def test_player_has_empty_battleship2_string player = Player.new assert_equal "", player.battleship2 end def test_player_has_empty_rounds_on_target player = Player.new assert_equal [], player.rounds_on_target end def test_player_can_create_ships skip 'Skipped because test requires User Input' player = Player.new player.create_ships assert_equal 3, player.battleship.length assert_equal 2, player.destroyer.length end def test_player_can_create_destroyer skip 'Skipped because test requires User Input' player = Player.new player.create_destroyer assert_equal 2, player.destroyer.length end def test_player_can_make_first_destroyer_coord skip 'Skipped because test requires User Input' player = Player.new player.make_first_destroyer_coordinates assert_equal 1, player.destroyer.length end def test_player_can_make_second_destroyer_coord skip 'Skipped because test requires User Input' player = Player.new player.make_second_destroyer_coordinates assert_equal 1, player.destroyer.length end def test_player_can_make_battleship skip 'Skipped because test requires User Input' player = Player.new player.create_battleship assert_equal 3, player.battleship.length end def test_player_can_make_first_battleship_coord skip 'Skipped because test requires User Input' player = Player.new player.make_first_battleship_coordinates assert_equal 1, player.battleship.length end end
true
12affa147e35ae30070be410e0d1524de88fc402
Ruby
joneslee111/battle
/app.rb
UTF-8
797
2.703125
3
[]
no_license
require 'sinatra/base' require 'player' require 'game' class Battle < Sinatra::Base enable :sessions get '/' do erb :index end post '/names' do $p1 = Player.new(params[:p1_name]) # session allows it to exist for length of session $p2 = Player.new(params[:p2_name]) # params exist in length of request and available in /names $game = Game.new($p1, $p2) redirect to('/play') # end get '/play' do @p1_name = $game.players.first.name @p2_name = $game.players.last.name erb :play end get '/attack' do @p1_name = $game.players.first.name @p2_name = $game.players.last.name $game.attack($game.players.last) erb :attack end # start the server if ruby file executed directly run! if app_file == $0 end
true
ca6dbcc58edba423fcafc63e0f89c9aa4255e34e
Ruby
bonzouti/Eventbrite
/spec/models/user_spec.rb
UTF-8
1,730
2.671875
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do before(:each) do @user = User.create(first_name: "John", last_name: "Doe", description: "jambon de parme car on a besoin de plus de text") end context "validation" do it "is valid with valid attributes" do expect(@user).to be_a(User) expect(@user).to be_valid end describe "#first_name" do it "should not be valid without first_name" do bad_user = User.create(last_name: "Doe") expect(bad_user).not_to be_valid # test très sympa qui permet de vérifier que la fameuse formule user.errors retourne bien un hash qui contient une erreur concernant le first_name. expect(bad_user.errors.include?(:first_name)).to eq(true) end end describe "#last_name" do it "should not be valid without last_name" do bad_user = User.create(first_name: "John") expect(bad_user).not_to be_valid expect(bad_user.errors.include?(:last_name)).to eq(true) end end describe "#description" do it "should not be empty" do invalid_user = User.create(first_name: "John", last_name: "Doe") expect(invalid_user).not_to be_valid expect(invalid_user.errors.include?(:description)).to eq(true) end end end context "associations" do describe "event" do it "should have_many events" do event = Event.create(user: @user, start_date: "21-11-2020", duration: 2200, title: "cats can fly woohoo", description: "Mathieu dit que les chats ne peuvent pas voler et ne voleraient jamais!!!", price: 100, location:"New York") expect(@user.events.include?(event)).to eq(false) end end end end
true
2b11099bbf2cf1cea07277ee4b2a5e917100e3b5
Ruby
rubberyuzu/sorting_implementation
/quicksort/quicksort_2.rb
UTF-8
464
3.828125
4
[]
no_license
class QuickSort def self.sort(arr) if arr.length <= 1 return arr else pivot = arr[0] arr.delete_at(0) # remove the pivot less = [] greater = [] arr.each do |el| if el <= pivot less << el else greater << el end end sorted_array = [] sorted_array << self.sort(less) sorted_array << pivot sorted_array << self.sort(greater) sorted_array.flatten! end end end p QuickSort.sort([1,5,7,2,4,8,3,7])
true
32be4ccc5d28883cc2c0414d8df4c83d8acda0a8
Ruby
shiningflint/house.rb
/house.rb
UTF-8
272
2.71875
3
[]
no_license
require "./room" require "./speaker" require "./mom" class House def initialize @lr = Room.new "Living Room" @kitchen = Room.new "Kitchen" @mom = Mom.new "Liz" @speaker = Speaker.new "Boombastic" end attr_accessor :mom, :lr, :kitchen, :speaker end
true
0521de205bd63b33350efbc4836d53864798d65a
Ruby
lyuehh/program_exercise
/ruby/ruby_test/2/socket3clict.rb
GB18030
303
2.84375
3
[]
no_license
#һĴ require 'socket' SERVER_ADDRESS = '127.0.0.1' SERVER_PORT = 30000 socket = TCPSocket.new(SERVER_ADDRESS,SERVER_PORT) read = Thread.new do while socket.gets print 'Ӧ: ' puts $_ end end while gets socket.puts($_) end socket.close
true
6863964c4844645b1cca1b69048242d89924fab2
Ruby
SheefaliT/CSCI3308
/RubyA1/RubyAssignmentP2.rb
UTF-8
800
4.90625
5
[]
no_license
#Part 2: Strings class Palindrome def initialize(string, tempvar) @string = string.downcase #input, one @ is a class variable @string = string.gsub(/[\s \W]/, '') #anything not a character, and replaces it with nothing, two pairs of quotes @tempvar = string.reverse! #trolls takes string and replaces it permanently (that's what ! does) @tempvar = string.gsub!(/[\s \W]/, '') #troll rips out anything that's not a character end def print puts "Word is #{@string}" #run print puts "Reverse is #{@tempvar}" #run tempvar end def compare #if string is = trolls, then print true, otherwise print lies if @string == @tempvar puts "TRUE" return true else puts "BOO" return false end end end wat = Palindrome.new("CARS AND SCAR", "Placeholder") #test code wat.print wat.compare
true
a7e5bfa06159460e8f78bea2bf43ca22ad7ab581
Ruby
julesnuggy/oystercard_challenge_FINAL
/lib/journey.rb
UTF-8
575
3.28125
3
[]
no_license
# Journey class definiation # This takes care of all journey related things and should return journey info # when referred to class Journey attr_reader :fare, :entry_station, :exit_station MIN_FARE, PENALTY = 1, 6 def initialize(station = nil) @entry_station = station end def finish_journey(station = nil) @exit_station = station calc_fare end def calc_fare @fare = completed? ? MIN_FARE + (@entry_station.zone - @exit_station.zone).abs : PENALTY end private def completed? !(@entry_station.nil? || @exit_station.nil?) end end
true
ca0f0c23b73b26034f050f4fb221955d238ee1ec
Ruby
skylerto/aem
/lib/aem/cli.rb
UTF-8
4,031
2.59375
3
[]
no_license
require 'json' require 'thor' require 'yaml' module Aem # The CLI interface # # @author Skyler Layne class CLI < Thor def initialize(*args) super $thor_runner = false opts = Aem::FileParse.new.read if opts.nil? puts "must have a config file: run aem setup" else @info = Aem::Info.new opts @c = Aem::AemCmd.new @info end end # gets the info used in the configuration desc "info", "gets the info used in the configuration" option :profile def info profile = options[:profile] res = @info if profile opts = Aem::FileParse.new.read profile if opts.nil? puts 'must have a config file: run aem setup' else res = Aem::Info.new opts end end puts res end # starts the setup process desc "setup", "starts the setup process" def setup url = ask("AEM URL:") username = ask("AEM Username:") password = ask("AEM Password:") contents = { 'url' => url, 'username' => username, 'password' => password } if File.exist?("#{ENV['HOME']}/.aem.yaml") yes = ask("#{ENV['HOME']}/.aem.yaml exists, would you like to overwrite it (Yn)?") if yes && yes.eql?('Y') puts "overwriting: #{contents.to_yaml} to #{ENV['HOME']}/.aem.yaml" opts = Aem::FileParse.new.create contents else puts "Ok, we'll keep your config" end else puts "writing: #{contents.to_yaml} to #{ENV['HOME']}/.aem.yaml" opts = Aem::FileParse.new.create contents end end # gets a list of all the packages available on AEM server desc "packages", "gets a list of all the packages available on AEM server" option :profile def packages puts cmd(options).list_packages end # searches for a package based on VALUE, KEY defaulting to name property desc "package VALUE KEY", "searches for a package based on VALUE, KEY defaulting to name property" option :profile def package name, property='name' puts cmd(options).package_info name, property end # builds a NAME desc "build NAME", "builds a NAME package" option :profile def build package, group='' puts JSON.parse cmd(options).build_package(package).body end # downloads a specific NAME to a specific PATH defaulting to the current directory desc "download NAME GROUP PATH", "downloads a specific NAME package from a group, to a specific PATH defaulting to the current directory" option :profile def download package, path='.' puts cmd(options).download_package(package, path) end # uploads the PATH with the NAME desc "upload PATH NAME", "uploads the PATH with the NAME" option :profile def upload file, name puts cmd(options).upload_package(file, name).body_str end # installs a NAME desc "install NAME", "installs a NAME package from a GROUP" option :profile def install package puts cmd(options).install_package(package) end # tree activates a list of PATHS desc "activate PATHS", "tree activates a list of PATHS" option :profile option :paths option :all def activate *paths modified = options[:all] ? 'false' : 'true' res = cmd(options).activate_paths(paths, modified) res = res.flatten unless res.nil? if options[:paths] out = [] res.each do |path| if path['status'].eql? 'Activate' out << path['path'] end end res = out end puts res end private def cmd options profile = options[:profile] res = @c if profile opts = Aem::FileParse.new.read profile if opts.nil? puts 'must have a config file: run aem setup' else info = Aem::Info.new opts res = Aem::AemCmd.new info end end return res end end end
true
1e5e8459329ec15831107d406adb1027dca326f5
Ruby
gnoll110/video_stick
/lib/video_stick.rb
UTF-8
197
2.53125
3
[ "MIT" ]
permissive
require "video_stick/version" require "video_stick/builder" module VideoStick class Chatter def say_hello puts 'This is video_stick. Coming in loud and clear. Over.' end end end
true
0d028842887e7bdb9d32706e450a0082dcfe4de1
Ruby
joesustaric/bowling-kata-ruby
/test/game_test.rb
UTF-8
1,716
2.796875
3
[ "MIT" ]
permissive
require 'minitest/spec' require 'minitest/autorun' require_relative '../lib/game' require_relative 'minitest_helper' describe Game do let(:perfect_game_rolls) { [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] } let(:perfect_game_score) { 300 } let(:worst_game_rolls) { [0,0, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0] } let(:worst_game_score) { 0 } let(:all_spare_rolls) { [ 5,5, 7,3, 3,7, 5,5, 0,10, 9,1, 9,1, 1,9, 2,8, 6,4, 1] } let(:all_spare_score) { 143 } let(:random_game) { [10, 0,1, 4,2, 10, 9,0, 8,0, 0,0, 5,5, 4,2, 10,0,1 ] } let(:random_game_score) { 85 } before do @game = Game.new end describe 'a new game' do it 'should set up the correct amount of frames' do @game.frames.size.must_equal 10 end end describe 'the perfect game' do before do perfect_game_rolls.each do |roll| @game.bowl roll end end it 'should calculate the correct score' do @game.score.must_equal perfect_game_score end end describe 'the worst game' do before do worst_game_rolls.each do |roll| @game.bowl roll end end it 'should calculate the correct score' do @game.score.must_equal worst_game_score end end describe 'the every frame is a spare' do before do all_spare_rolls.each do |roll| @game.bowl roll end end it 'should calculate the correct score' do @game.score.must_equal all_spare_score end end describe 'a random game' do before do random_game.each do |roll| @game.bowl roll end end it 'should calculate the correct score' do @game.score.must_equal random_game_score end end end
true
d858d04885f86d0c95c3812edbff627fdde36453
Ruby
thyagobr/verwandlung
/producer/producer.rb
UTF-8
1,271
2.6875
3
[]
no_license
require "kafka" require "oj" require 'faker' KAKFA_URLS = ["localhost:9092"] PRODUCER_NAME = 'producer' TOPIC = 'verwandlung' kafka = Kafka.new(["localhost:9092"], client_id: PRODUCER_NAME) kafka.alter_topic(TOPIC, "max.message.bytes" => 10_000_000) producer = kafka.async_producer( delivery_threshold: 20, # Delivery once N msg have been buffered. delivery_interval: 20, # Trigger a delivery every N seconds. max_buffer_size: 5_000, # Allow at most 5K messages to be buffered. max_buffer_bytesize: 100_000_000, # Allow at most 100MB to be buffered. compression_codec: :gzip, compression_threshold: 10, ) # Handling Ctrl-C cleanly in Ruby the ZeroMQ way: trap("INT") { puts "Shutting down."; producer.shutdown; exit} puts "Starting up Kafka: #{KAKFA_URLS} :: Topic: #{TOPIC}\n" loop do num_events = rand(1...10) print "\rCreated [#{num_events}] events...." num_events.times do event = { current_user: Faker::Name.first_name, item: Faker::Construction.material, description: "Item #{Faker::Verb.past_participle}", labels: "[:#{Faker::Verb.past_participle}]" } data = Oj.dump(event) producer.produce(data, topic: TOPIC, partition_key: rand(1...10)) end sleep(0.1) end
true
e734a1bbd805f00c52d7d00ad2acad3d75092edf
Ruby
jbrunton/jira-team-metrics
/app/stats/jira_team_metrics/trend_builder.rb
UTF-8
989
3.140625
3
[ "MIT" ]
permissive
class JiraTeamMetrics::TrendBuilder def pluck(&pluck_block) @pluck_block = pluck_block self end def map(&map_block) @map_block = map_block self end def analyze(series) values = series.map{ |item| @pluck_block.call(item) } series.each_with_index.map do |item, index| sample = JiraTeamMetrics::TrendBuilder.pick_sample(values, index) @map_block.call(item, sample.mean, sample.standard_deviation) end end def self.sample_size(series_size) sample_size = (series_size * 0.2).to_i sample_size = sample_size + 1 if sample_size.even? [sample_size, 5].max end def self.pick_sample(values, index) sample_size = self.sample_size(values.length) start_index = [0, index - sample_size / 2 - 1].max end_index = start_index + sample_size while end_index > values.length start_index = start_index - 1 if start_index > 0 end_index = end_index - 1 end values[start_index..end_index - 1] end end
true
f129054f75e7cdc7fa6eb5f8e4a3ba6e6ad48b78
Ruby
wengkhing/tictactoe
/app/models/user.rb
UTF-8
773
2.75
3
[]
no_license
class User < ActiveRecord::Base # Remember to create a migration! has_many :won_games, class_name: 'Game', foreign_key: 'winner_id' has_many :games_played_as_p1, class_name: 'Game', foreign_key: 'p1_id' has_many :games_played_as_p2, class_name: 'Game', foreign_key: 'p2_id' def authenticate(pw) self.password == pw end def isHost?(game_id) Game.find(game_id).p1.id == self.id end def isPlayer(game_id) game = Game.find(game_id) if game.p1.id == self.id 1 elsif game.p2.id == self.id 2 else 0 end end def turn?(game_id) game = Game.find(game_id) case isPlayer(game_id) when 1 return game.turn == 1 when 2 return game.turn == 2 else return false end end end
true
fbb3b2cbf42e2283f0374e33af9b8991c2d6de1f
Ruby
jeffmcfadden/colormap
/lib/colormap/colormap.rb
UTF-8
1,858
3.40625
3
[ "MIT" ]
permissive
require 'color' module Colormap include ::Color class Colormap attr_accessor :waypoints def initialize( waypoints ) self.waypoints = waypoints end def color( value: value ) value = value.to_f if value < self.waypoints[0][:value] value = self.waypoints[0][:value] elsif value > self.waypoints.last[:value] value = self.waypoints.last[:value] end p = 0 n = 0 self.waypoints.each_with_index do |w,i| p = i if value >= self.waypoints[i][:value].to_f && value <= self.waypoints[i+1][:value].to_f n = i + 1 break end end prevColor = ::Color::RGB.from_html( self.waypoints[p][:color] ) nextColor = ::Color::RGB.from_html( self.waypoints[n][:color] ) distance = (value - self.waypoints[p][:value].to_f) / ( self.waypoints[n][:value].to_f - self.waypoints[p][:value].to_f ) self.color_between( color_1:prevColor, color_2:nextColor, distance:distance ) end def color_between( color_1: color_1, color_2: color_2, distance: distance ) color_1 = color_1.to_hsl color_2 = color_2.to_hsl h1 = color_1.hue; s1 = color_1.saturation; b1 = color_1.luminosity; h2 = color_2.hue; s2 = color_2.saturation; b2 = color_2.luminosity; if h2 == 1.0 h2 = 0.0 end if h1 == 1.0 h1 = 0.0 end h = h1 - ((h1 - h2) * ( distance )) #Color 2.hue should be higher because hue goes down as temp goes up s = color_1.saturation + ((color_2.saturation - color_1.saturation).abs * ( distance )) b = color_1.luminosity + ((color_2.luminosity - color_1.luminosity).abs * ( distance )) return ::Color::HSL.new( h, s, b ) end end end
true
4c3739d06a345ad376a61668139c541ed3b30867
Ruby
augustoppimenta/Cientec
/02.rb
UTF-8
151
3.375
3
[]
no_license
numer = rand(1..10) puts "Numer #{numer}" if numer > 2 puts "O numero #{numer} é maior que 2" else puts "O numero #{numer} é menor que 2" end
true
6c4dd9868dd907f088b7a1d5a13f8dd2bbd7550e
Ruby
irenafnaf/Ironhack
/week_3/user_password_authenticator/app.rb
UTF-8
936
3.59375
4
[]
no_license
# app.rb require_relative("lib/authenticator.rb") require_relative('lib/word_stuff.rb') require_relative('lib/counter_picker.rb') auth = Authenticator.new("Josh", "swordfish") # Get login credentials puts "username?" username_input = gets.chomp puts "password?" password_input = gets.chomp if auth.verify(username_input, password_input) # Call upon Authenticator to verify login credentials puts "Welcome back, #{username_input}" puts "Enter a sentence" sentence_input = gets.chomp # Do word counter things my_counter = WordStuff.new(sentence_input) puts "Do you want to: \n count words / \n count letters / \n reverse sentence / \n make them uppercase / \n make them lowercase" answer = gets.chomp counter_picker = CounterPicker.new(answer, my_counter) counter_picker.perform_operation else puts "Your credentials are't valid. Try Again!" # Do something to tell the User their credentials aren't valid end
true
73b0bb6df7f07381a56a68299ceafdaf14b64f98
Ruby
Youngermaster/Learning-Programming-Languages
/Ruby/Procedures/Procedures.rb
UTF-8
310
4
4
[ "MIT" ]
permissive
class Array def iterar block self.each_with_index do |n,y| self[y] = block.call n end end end array = [1, 2, 3, 4, 5] pow = Proc.new do |n| n**2 end plus_1 = Proc.new do |number| number + 1 end array.iterar plus_1 array.iterar pow for i in array puts i end
true
87b9901dbad57585b859dffc6affc27a1a27e518
Ruby
nickpalenchar/hacker-contacts
/lib/guide.rb
UTF-8
796
3.390625
3
[ "MIT" ]
permissive
require 'contact' class Guide def initialize(path=nil) # locate the restaurant text file at path Contact.filepath = path if Contact.file_usable? puts "[guide.rb] using file `" + path + "`" elsif Contact.create_file puts "[guide.rb]: created new Contact File" else puts "Exiting.\n\n" exit! end end def launch! introduction # action loop # what do you want to do (list, fine, add, quit) # do that action conclusion end def introduction puts "\n\n" puts "________________________________" puts "| <<< Haxor Contacts >>> |" puts "|------------------------------|" puts "| Your contacts in the shell |" puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" end def conclusion puts "Bye." end end
true
142ec974f4a07dcd6d531f0f770dc143f570aa6d
Ruby
zdennis/practice-guitar_tabs_bdd
/lib/guitar_tabs/tab.rb
UTF-8
142
2.703125
3
[]
no_license
class Tab attr_reader :notes_to_be_played def initialize(tablature, parser) @notes_to_be_played = parser.parse(tablature) end end
true
f74c409721594e3c593dc02b1953e5ee8c5effb7
Ruby
justdroo/mirror-mirror
/src/trivia/03_truthiness_control_flow/03_quiz_key_a.rb
UTF-8
2,670
3.34375
3
[]
no_license
@quiz_key_a = { section_title: "Truthiness Mini Trivia", instructions: "This is a hard one! Remember to talk it out and if you get stuck, ask for help or use the internet.", quiz: [ { type: "multiple_choice", question: "What is a boolean?", answers: { a: "A binary representation of true or false", b: "Where ghosts go to hang out", c: "A 0 or 1 predictor", d: "A method" }, solution: "a" }, { type: "multiple_choice", question: "A double bang operator (!!) coerces data into:", answers: { a: "True", b: "False", c: "True or False", d: "True or False or nil" }, solution: "c" }, { type: "multiple_choice", question: "A string in ruby is considered:", answers: { a: "Truthy", b: "Falsey", c: "Truthy unless it is empty", d: "Falsey unless it is empty" }, solution: "a" }, { type: "multiple_choice", question: "What are the only values in Ruby that are considered falsey?", answers: { a: "Empty Strings and 0", b: "False and nil", c: "0 and nil ", d: "False, 0 and nil" }, solution: "b" }, { type: "multiple_choice", question: "What is the return value of the statement: 6 > 9 || 4 < 5", answers: { a: "True", b: "False", c: "nil" }, solution: "a" }, { type: "multiple_choice", question: "What is the return value of the statement: 2 > 5 && 7 < 12", answers: { a: "True", b: "False", c: "nil" }, solution: "b" }, { type: "multiple_choice", question: "What is the return value of the statement: 7 == 7.5", answers: { a: "True", b: "False", c: "nil" }, solution: "b" }, { type: "multiple_choice", question: "What is the return value of the statement: !'Hello World'", answers: { a: "True", b: "False", c: "nil" }, solution: "b" }, { type: "multiple_choice", question: "What is the return value of the statement: !! 7 < 3", answers: { a: "True", b: "False", c: "nil" }, solution: "b" }, { type: "multiple_choice", question: "What is the return value of the statement: 81 >= (!45 - 6) || (!8 && !!'hello world')", answers: { a: "True", b: "False", c: "nil" }, solution: "c" } ] }
true
cf136e83b2df15b20fa4db0c50e88afaee281110
Ruby
gerard-morera/altmetric
/02-refactoring/lib/date_range_identifier.rb
UTF-8
695
3.09375
3
[]
no_license
class DateRangeIdentifier def initialize start_date, end_date @start_date = start_date @end_date = end_date end def call if same_year_and_same_day_dates? "day_format" elsif same_year_and_same_month_dates? "month_format" elsif same_year_dates? "year_format" else "other_format" end end private attr_reader :start_date, :end_date def same_year_and_same_day_dates? start_date == end_date end def same_year_and_same_month_dates? same_month_dates? && same_year_dates? end def same_month_dates? start_date.month == end_date.month end def same_year_dates? start_date.year == end_date.year end end
true
c6bd0f1d60c51425d58c8979cc82da41d48cc674
Ruby
NoahZinter/fte_2103
/spec/event_spec.rb
UTF-8
7,677
3.328125
3
[]
no_license
require './lib/item' require './lib/food_truck' require './lib/event' describe Event do it 'exists' do event = Event.new("South Pearl Street Farmers Market") expect(event).is_a? Event end it 'has a name' do event = Event.new("South Pearl Street Farmers Market") expect(event.name).to eq "South Pearl Street Farmers Market" end it 'starts with an empty array of food trucks' do event = Event.new("South Pearl Street Farmers Market") expect(event.food_trucks).to eq ([]) end describe '#add_food_truck' do it 'adds food trucks to array' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.food_trucks).to eq [food_truck1, food_truck2, food_truck3] end end describe '#food_truck_names' do it 'returns an array of food truck names' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.food_truck_names).to eq(["Rocky Mountain Pies", "Ba-Nom-a-Nom", "Palisade Peach Shack"]) end end describe '#items' do it 'returns a list of items being sold' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.items).to eq ([item1, item2, item4, item3] ) end end describe '#trucks_that_sell' do it 'returns food trucks which sell an item' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.food_trucks_that_sell(item1)).to eq([food_truck1, food_truck3]) expect(event.food_trucks_that_sell(item4)).to eq([food_truck2]) end end describe 'total quantity' do it 'returns the total quantity of item at event' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.total_quantity(item1)).to eq 100 end end describe '#total_inventory' do it 'returns a nested hash of items with total quantity' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expected = {item1 => { :quantity => 100, :food_trucks => [food_truck1, food_truck3]}, item2 => {:quantity => 7, :food_trucks => [food_truck1]}, item4 => {:quantity => 50, :food_trucks => [food_truck2]}, item3 => {:quantity => 25, :food_trucks => [food_truck2]}} expect(event.total_inventory).to eq (expected) end end describe '#overstocked items' do it 'returns items sold by more than 1 truck and over 50' do event = Event.new("South Pearl Street Farmers Market") food_truck1 = FoodTruck.new("Rocky Mountain Pies") item1 = Item.new({name: 'Peach Pie (Slice)', price: "$3.75"}) item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'}) item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"}) item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"}) food_truck1.stock(item1, 35) food_truck1.stock(item2, 7) food_truck2 = FoodTruck.new("Ba-Nom-a-Nom") food_truck2.stock(item4, 50) food_truck2.stock(item3, 25) food_truck3 = FoodTruck.new("Palisade Peach Shack") food_truck3.stock(item1, 65) event.add_food_truck(food_truck1) event.add_food_truck(food_truck2) event.add_food_truck(food_truck3) expect(event.overstocked_items).to eq ([item1]) end end end
true
ec5b215b210f149b7e8374502d99a0700a8ed9dc
Ruby
jrayala-livecode/Prueba_Ruby
/photos_count.rb
UTF-8
163
2.703125
3
[]
no_license
def photos_count(req) photos = req["photos"] cuentas = Hash.new(0) photos.each { |photo| cuentas[photo["camera"]["name"]] += 1 } return cuentas end
true
4ab3c4f6d1881dcf86d23815096a3b0f76de2653
Ruby
jdashton/glowing-succotash
/daniel/HeadFirst/ch13_jda/lib/list_with_commas.rb
UTF-8
690
3.75
4
[ "MIT" ]
permissive
# How to join list items class ListWithCommas attr_accessor :items def join case items.length when 1 then items[0] when 2 then items.join(' and ') else (items[0..-2] << "and #{ items.last }").join(', ') end end end if $PROGRAM_NAME == __FILE__ two_subjects = ListWithCommas.new two_subjects.items = ['my parents', 'a rodeo clown'] puts "A photo of #{ two_subjects.join }" three_subjects = ListWithCommas.new three_subjects.items = ['my parents', 'a rodeo clown', 'a prize bull'] puts "A photo of #{ three_subjects.join }" one_subject = ListWithCommas.new one_subject.items = ['a rodeo clown'] puts "A photo of #{ one_subject.join }" end
true
91270870470f5e076156ccaa576f72e727ee0fcb
Ruby
bayendor/eventreporter
/lib/message_printer.rb
UTF-8
2,463
3.390625
3
[]
no_license
require './lib/repository' class MessagePrinter def initialize(output_stream) @output_stream = output_stream end def intro @output_stream.puts 'Welcome to Event Reporter.' program_instructions end def program_instructions @output_stream.puts 'Would you like to (l)oad a file, ask for (h)elp, or (q)uit?' end def command_request print 'Enter your command: ' end def loaded(file) @output_stream.puts "#{file} is now loaded." end def file_not_found @output_stream.puts 'File not found.' end def results(count) @output_stream.puts "Your search returned #{count} results." end def results_clear @output_stream.puts 'The queue has been cleared.' end def results_count(count) @output_stream.puts "There are #{count} results in the queue." end def results_print @output_stream.puts 'Your results:' end def help @output_stream.puts "Choose from the following help topics: find, load, queue, queue clear, queue count, queue print, save. You may type 'Help [topic]' at anytime." end def help_find @output_stream.puts ".....FIND: To use the find command, simply type 'FIND [category] [entry]'. Choose from the following categories: first_name, last_name, email_address, phone_number, street, city, state or zipcode. An entry would be information like Massachusetts or 63130. Ex. FIND FIRST_NAME IGOR would return all file listings that include gentlemen with the first name Igor." end def help_load @output_stream.puts ".....LOAD: To load a file, type 'LOAD [filename]'. Ex. LOAD EVENT_ATTENDEES.CSV" end def help_queue @output_stream.puts ".....QUEUE: So you need help with the queue, eh? Let's talk..." end def help_queue_clear @output_stream.puts '.....QUEUE CLEAR: Info about clearing the queue...' end def help_queue_count @output_stream.puts '.....QUEUE COUNT: Info about the queue count...' end def help_queue_print @output_stream.puts '.....QUEUE PRINT: Info about printing your queue...' end def help_save @output_stream.puts '.....SAVE: Info about saving...' end def ending @output_stream.puts 'Thanks for using Event Reporter. Goodbye.' end def not_a_valid_command_message @output_stream.puts "That's not a valid command. Please try again. You may ask for (h)elp at any time." end def specify_filename @output_stream.puts 'Please specify a filename.' end end
true
3947118d2a89f03a08aae4b8228e9adfeb97c5ca
Ruby
suga/changeLogDeploy
/spec/libs/validators/validator_path_spec.rb
UTF-8
1,849
2.578125
3
[]
no_license
require File.dirname(__FILE__) + "/../../../libs/validators/validator_path" require 'tempfile' describe ValidatorPath do before(:each) do @path_not_existis = '/tmp/not_exists.yml' @file = Tempfile.new(['20130516','.yml']) @path_exists = @file.path end after(:each) do @file.close @file.unlink end it "The file exists, may not throw exception" do validator = ValidatorPath.new(@path_exists) expect { validator.config_exists_in_file_system? }.to_not raise_error end it "The file does not exist, then we have an exception" do validator = ValidatorPath.new(@path_not_existis) expect { validator.config_exists_in_file_system? }.to raise_error(FileException) expect { validator.config_exists_in_file_system? }.to raise_error(/File not found. The specified file was/) end it "The file has read permission, we have no exception" do validator = ValidatorPath.new(@path_exists) expect { validator.the_file_has_permission_read? }.to_not raise_error end it "The file is writable for this, we have no exception" do validator = ValidatorPath.new(@path_exists) expect { validator.the_file_has_permission_write? }.to_not raise_error end it "The file is valid, we have no exception" do validator = ValidatorPath.new(@path_exists) expect { validator.is_valid? }.to_not raise_error end it "The file is not writable for this, we have exception" do FileUtils.chmod 0111, @path_exists validator = ValidatorPath.new(@path_exists) expect { validator.the_file_has_permission_write? }.to raise_error end it "The file has not read permission, we have exception" do FileUtils.chmod 0111, @path_exists validator = ValidatorPath.new(@path_exists) expect { validator.the_file_has_permission_read? }.to raise_error end end
true
bb5fa4578411a46caaa6588c464c738680b296a8
Ruby
hacaravan/advent-of-code
/Day_7/day_7_q_1.rb
UTF-8
1,553
3.65625
4
[]
no_license
# From a long list of rules on which bags can contain which other bags, # determine how many different kind of bags can eventually contain the given bag type # In this case, a bright gold bag input_file = './day_7_input' # This is list of all bags together with rules for what they can contain bag_rules_list = File.read(input_file).split("\n") # This is list of all the different bags, ignoring the rules attached to them # The list is already unique because of how the input file is set out bags_list = bag_rules_list.map { |line| line.partition(" bags").first } bag_contained_hash = {} bags_list.each { |bag| bag_contained_hash[bag] = [] } # The below adds all the first order container bags for each bag bag_rules_list.each do |line| container_bag = line.partition(" bags").first contained_bags = line.partition("contain ").last.split(/\d+ |[.,] *|bags*/).map(&:rstrip).reject{|bag| bag.empty? || bag == "no other"} contained_bags.each{ |bag| bag_contained_hash[bag] << container_bag } end # Run through and add all the bags that can contain any of the bags that contain the given bag, # then the bags that contain those, and so on until you get to bags which can't be held in any others check_bag = "shiny gold" while true do initial_array = bag_contained_hash[check_bag] initial_array.each {|bag| bag_contained_hash[check_bag] |= bag_contained_hash[bag]} break if bag_contained_hash[check_bag] == initial_array end puts "There are #{bag_contained_hash[check_bag].count} bags which can ultimately contain the #{check_bag} bag"
true
6b8e370b74b653142a4173c74f22c70d31404bb2
Ruby
hed911/applefakedata
/analyzer.rb
UTF-8
320
3.09375
3
[]
no_license
require 'csv' good_phones = 0 bad_phones = 0 CSV.foreach("dataset.csv", col_sep: ';', headers: true) do |row| performance = row[3] good_phones += 1 if performance == 'GOOD' bad_phones += 1 if performance == 'BAD' end puts "GOOD: #{good_phones}" puts "BAD: #{bad_phones}" puts "TOTAL: #{good_phones + bad_phones}"
true
476ea650a2f8ca06fbc8aa7fbbe67c8d1f7a0709
Ruby
kagemusha/speculator
/spec/scrape/stock_spec.rb
UTF-8
4,290
2.640625
3
[]
no_license
require 'spec_helper' #@SYMBOL = "msft" #@DOC = "http://quotes.wsj.com/#{@SYMBOL}/financials/quarter/income-statement" #puts "hello" #doc = Nokogiri::HTML( open @DOC ) #tables = Array.new #doc.search('table').each do|tbl| # #scrape #end QTR_TYPE = FinancialStatement::Q ANNUAL_TYPE = FinancialStatement::A PERIOD_TYPES =[QTR_TYPE,ANNUAL_TYPE] VALID_UNITS = ["Thousands","Millions","Billions"] SYMBOLS = ["msft","hpq","amd"] VALIDATION_SETS = { "msft"=>{:fy=>"June",:currency=>"USD", "mult"=>1}, "hpq"=>{:fy=>"October",:currency=>"USD", "mult"=>1}, "amd"=>{:fy=>"December",:currency=>"USD", "mult"=>1, "mult_cf_q"=>0.001}, "arc"=>{:fy=>"December",:currency=>"USD", "mult"=>0.001} } SYMBOLS = ["msft","hpq","amd"] #,#,# def test_statements(symbol, &test) specs = [WsjDataMappings::BS_SPECS, WsjDataMappings::PL_SPECS, WsjDataMappings::CF_SPECS] specs.each do |spec| PERIOD_TYPES.each do|period_type| url = WsjDataMappings.financials_url(symbol, spec[:url_frag], period_type) puts "url #{url}" page = Nokogiri::HTML(open url) tables = TableScraper.page_tables_to_arrays(page, "table.#{WsjDataMappings::TABLE_CLASS}") test.call VALIDATION_SETS[symbol], spec, period_type, tables end end end def test_get_stmt_params(validation_set, spec, period_type, tables) #puts "tables[0]: #{tables[0].inspect}" params_cell = tables[0][0] #header row of first table as array periods,fiscal_yr,currency,units = StockScrape.get_stmt_params period_type, params_cell #puts "periods,etc: #{periods.inspect}, #{fiscal_yr}, #{currency}, #{units}" periods.length.should==5 fiscal_yr.should==validation_set[:fy] currency.should==validation_set[:currency] stmt_specific_mult = "mult_#{spec[:abbr]}_#{period_type}" valid_mult = validation_set[stmt_specific_mult]|| validation_set["mult"] || 1 puts "mult_key: #{stmt_specific_mult}, #{valid_mult}" WsjDataMappings.multiplier(units).should==valid_mult VALID_UNITS.should include(units) end def stmt_test(stmt_specs, symbols) symbols.each do |symbol| PERIOD_TYPES.each do |period_type| StockScrape.get_financial_statement_data(symbol, stmt_specs, period_type) end end end describe Stock do before(:each) do end #it "should generate correct WSJ url" do # symbol = "msft" # spec = WsjDataMappings::BS_SPECS # url = WsjDataMappings.financials_url(symbol, spec[:url_frag], ANNUAL_TYPE) # url.should=="http://quotes.wsj.com/msft/financials/annual/balance-sheet" #end ##http://quotes.wsj.com/MSFT/financials/annual/balance-sheet ##http://quotes.wsj.com/MSFT/financials/quarter/balance-sheet ##http://quotes.wsj.com/MSFT/financials/annual/cash-flow ##http://quotes.wsj.com/MSFT/financials/annual/income-statement #DATES=[["January",1,31],["June",6,30],["December",12,31] ] #it "should get last day of period correctly" do # DATES.each do |date| # valid_date = Date.new(2012, date[1], date[2]) # puts "valid_date: #{valid_date}" # StockScrape.last_day_of_fiscal_year("2012", date[0]).should==valid_date # end #end #it "should return nil if no page given" do # #pending "add some examples to (or delete) #{__FILE__}" # TableScraper.page_tables_to_arrays(nil).should==nil #end # #it "should get approp num tables on each WSJ fin stmts page" do # test_statements(validation_data) { |spec, period_type, tables| tables.length.should==spec[:table_count] } #end it "should get correct statement params from stmt page" do symbols = ["msft","arc","amd"] symbols.each do |symbol| test_statements(symbol) { |validation_set, spec, period_type, tables| test_get_stmt_params(validation_set, spec, period_type, tables) } end end #it "should get correct bal sheet data from wsj" do # stmt_specs = WsjDataMappings::BS_SPECS # symbols = ["msft","hpq","amd"] # stmt_test(stmt_specs, symbols) #end # #it "should get correct p/l data from wsj" do # stmt_specs = WsjDataMappings::PL_SPECS # symbols = ["msft","hpq","amd"] # stmt_test(stmt_specs, symbols) #end # #it "should get correct cash flow data from wsj" do # stmt_specs = WsjDataMappings::BS_SPECS # symbols = ["msft"] #,"hpq","amd"] # stmt_test(stmt_specs, symbols) #end end
true
61c465c17450fdd011e2f8a3a91b32112c37ac3c
Ruby
jillirami/reverse_sentence
/lib/reverse_sentence.rb
UTF-8
1,107
4.1875
4
[]
no_license
# A method to reverse the words in a sentence, in place. # Time complexity: O(n^2) # Space complexity: O(1) def reverse_sentence(my_sentence) my_sentence = reverse_words(my_sentence) return string_reverse(my_sentence) end def reverse_words(my_words) return nil if my_words.nil? start_word = 0 end_word = 0 i = 0 unless my_words == nil length = my_words.length while i < length while my_words[i] == " " i += 1 end start_word = i while i < length && my_words[i] != " " i += 1 end end_word = i - 1 while end_word > start_word temp = my_words[start_word] my_words[start_word] = my_words[end_word] my_words[end_word] = temp start_word += 1 end_word -= 1 end end end return my_words end def string_reverse(my_string) return nil if my_string.nil? length = my_string.length i = 1 while i <= length/2 temp = my_string[i - 1] my_string[i - 1] = my_string[length - i] my_string[length - i] = temp i += 1 end return my_string end
true