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
b86bdf1ce9f76d49fe6dd02e517f7d37a3d25df5
Ruby
athio92/launchschool
/courses/100/L1T13/02_Variables/name.rb
UTF-8
152
3.484375
3
[]
no_license
puts "Type your first name" firstname = gets.chomp puts "Type your last name" lastname = gets.chomp 10.times {puts "Hello #{firstname} #{lastname}!"}
true
0b54d9725387a44ba88753e68e7acd32f85be6fb
Ruby
triedman99/project_cli_connect_four
/lib/board.rb
UTF-8
2,514
3.78125
4
[]
no_license
class Board attr_reader :board def initialize @board = Array.new(7){Array.new(7)} end def render puts puts "0 1 2 3 4 5 6" @board.each_with_index do |row, row_index| row.each_with_index do |col, col_index| col.nil? ? print("-".center(4)) : print(col.to_s.center(4)) end puts end end def add_piece(column, piece) if legal_move?(column) counter = 0 while @board[6 - counter][column] != nil counter += 1 end if counter == 7 puts "That column is full." false end @board[6 - counter][column] = piece true else false end end def winning_move?(piece) diagonal_win?(piece) || horizontal_win?(piece) || vertical_win?(piece) end def full_board? @board.each do |column| if column.any? {|piece| piece == nil} return false else true end end end def legal_move?(column) if within_valid?(column) true else false end end def within_valid?(column) if (0..6).include?(column) true else puts "# That space doesn't exist." false end end def diagonal_win?(piece) if up_diagonals?(piece) || down_diagonals?(piece) true end end def horizontal_win?(piece) @board.each do |column| 3.times do |index| if column[index..(index + 3)].all? {|element| element == piece} return true end end end false end def vertical_win?(piece) 6.times do |row| 4.times do |column| result = [] 4.times do |index| result << @board[column + index][row] end if result.all? {|element| element == piece} return true end end end false end def up_diagonals?(piece) 3.times do |row| 4.times do |column| result = [] 4.times do |index| result << @board[column + index][row + index] end if result.all? {|element| element == piece} return true end end end false end def down_diagonals?(piece) row_index = 3 while row_index <= 5 4.times do |column| result = [] 4.times do |index| result << @board[column + index][row_index - index] end if result.all? {|element| element == piece} return true end end row_index += 1 end false end end
true
b3f20f6900892181142b54c42a41b09a685463b0
Ruby
atsutsumi/mrs_client_s
/lib/mrscs/receiver.rb
UTF-8
2,248
2.640625
3
[]
no_license
# coding: UTF-8 require 'socket' module Mrscs # # Unixドメインソケットサーバを起動し外部からのデータを受信します。 # データを受信した後はこのクラスで保持するdelegateインスタンスに受信データを連携します。 # class Receiver # アクセサ定義 attr_accessor :delegate # # 初期化処理 # # ==== Args # _options_ :: 起動時の設定 # ==== Return # ==== Raise def initialize(options) @options = options @sock_path = options['unix_socket'] # データ受信時のデリゲートクラス @delegate = nil @log = Mrscs.logger end # # Unixドメインソケットサーバを起動します。 # # ==== Args # ==== Return # ==== Raise def start @log.info("データ受信スレッド開始...") while true sleep(0.1) # 前回のソケットファイルを削除 if File.exist? @sock_path File.unlink @sock_path end # UnixDomainソケットをオープン UNIXServer.open(@sock_path) {|serv| # serv->UNIXServerインスタンス @log.info("ソケットをオープンしました。") while true sleep(0.1) begin @log.info("データ受信待ち...") # データを受信 s = serv.accept data = s.read @log.info("データを受信しました。データ長->#{data.length}") # 受信したデータをデリゲートに通知 notify_delegate(data) rescue => exception @log.warn("データ受信待ちでエラーが発生しました。") ensure unless s.nil? s.close end end end } end end # # デリゲート通知 # # ==== Args # _data_ :: デリゲートに通知するデータ # ==== Return # ==== Raise def notify_delegate(data) unless @delegate.nil? @delegate.request_send(data) end end end # Receiver end # Mrscs
true
63265ac2b53c35918586a4633df95e13a10a4950
Ruby
arturaz/custom_serialize
/lib/arturaz/custom_serialize.rb
UTF-8
1,957
2.65625
3
[ "MIT" ]
permissive
module Arturaz module CustomSerialize module ClassMethods # Serialize attributes in custom way instead of using default #serialize # which always serializes to YAML. This method allows you to serialize # in your own kind of ways. # # For example if you want serialize +Array+ to comma separated string # you can use: # # <pre> # custom_serialize :alliance_planet_player_ids, :alliance_ship_player_ids, # :serialize => Proc.new { |value| # value.blank? ? nil : value.join(",") # }, # :unserialize => Proc.new { |value| # value.nil? ? [] : value.split(",").map(&:to_i) # } # </pre> # # Where _alliance_planet_player_ids_ and _alliance_ship_player_ids_ are # attribute names. # # Default values for :serialize and :unserialize converts to and from # JSON. # def custom_serialize(*args) options = args.last.is_a?(Hash) ? args.pop : {} options.reverse_merge!( :serialize => Proc.new { |value| value.to_json }, :unserialize => Proc.new { |value| JSON.parse(value) } ) attributes = args after_find :custom_unserialize_attributes define_method(:custom_unserialize_attributes) do attributes.each do |attribute| send(:"#{attribute}=", options[:unserialize].call(send(attribute))) changed_attributes.delete attribute.to_s end super() if defined?(super) end define_method(:custom_serialize_attributes) do attributes.each do |attribute| send(:"#{attribute}=", options[:serialize].call(send(attribute))) end true end before_save :custom_serialize_attributes # Restore attributes changed by #custom_serialize_attributes after_save :custom_unserialize_attributes end end end end
true
b4aeaf69dae79d5583e2a52e8db360a6647639a4
Ruby
gellieb/workspace
/workspace_1/002-chrispine/7.5.3-deaf-grandma-extended-2.rb
UTF-8
998
3.96875
4
[]
no_license
# What if Grandma doesn’t want you to leave? # When you shout BYE, she could pretend not to hear you. # Change your previous program so that you have to shout # BYE three times in a row. Make sure to test your program: # if you shout BYE three times but not in a row, you should # still be talking to Grandma.” puts "Hi grandma!" puts "Hello there, grandbaby" puts "Did you say something??" count = 0 while TRUE gbaby = gets.chomp if gbaby == "BYE" count = count + 1 else gbaby != "BYE" count = 0 end if count >=3 puts "Bye, darling. I do love when you come see me :)" puts "Come see me again soon!" break end if gbaby != gbaby.upcase puts "HUH?! SPEAK UP, BABY!" puts "What\'d you say?" else puts "NO, NOT SINCE " + (1930+ rand(21)).to_s + "!" puts "hmm??" end end #11:40 (define count=0 at start & if not 3 consecutive 'BYE's)
true
86bdbb2437340b0ef714e4b894bc421799421649
Ruby
macZombie/Ruby-
/csvFile.rb
UTF-8
8,741
2.640625
3
[]
no_license
#!/usr/bin/ruby #File: csvFile.rb # # csvFile.rb class CsvFile < CustomFile @bufferFile = "" @bufferFileName = "" @indexArray = Array.[] def initialize(fileName) super(fileName,"Comma Separated Variables / Sheet") @indexArray = [""] end def getString myString = @file.gets return(myString) end def getTopLine openRead() topLine = @file.gets if (topLine != nil ) topLine = topLine.chomp end if (topLine != nil ) topLine = topLine.strip end close return topLine end def populateIndexArray(idString) column = getColumn(idString) openRead dummyString = @file.gets thisLine = "" @indexArray.pop ; # remove dummy string first begin thisLine = @file.gets if ( thisLine != nil ) thisBitFieldList = thisLine.split(",") thisBitField = thisBitFieldList[column] # Special Hack Here..... thisBitField = thisBitField.sub("[","_") thisBitField = thisBitField.sub("]","_") thisBitField = thisBitField.sub(":","_") thisBitField = thisBitField.sub("<","_") thisBitField = thisBitField.sub(">","_") thisBitField = thisBitField.downcase @indexArray.push(thisBitField) end end while ( thisLine != nil ) close return end def dumpIndexArray print "\n\nINFO: ",getName,"'s indexArray" @indexArray.each do |item| print "\n",item end return end def getIndexArray return ( @indexArray ) end def columnCount topLine = getTopLine() count = topLine.count(",") return count end def rowCount openRead() count = 0 begin thisString = @file.gets count = count + 1 end while ( thisString != nil ) close() return count end def getCell(thisString,n) returnedString = "NOT_FOUND" if ( thisString != nil ) thisList = thisString.split(",") thisElement = thisList[n] if ( thisElement != nil ) returnedString = thisElement end end return(returnedString); end def getColumn(search) column = -1 topLine = getTopLine position = topLine.index(search) index = 0 topLineList = topLine.split(",") column = topLineList.index(search) if ( column == nil ) column = -1 print "\n***** ERROR: getColumn - Can't find a column named ",search," in >",topLine,"<" exit end return column end def getColumnName(number) topLine = getTopLine() columnName = getCell(topLine,number) return columnName end def search(reply, reference ,referenceItem ) # search for the 1st argument where the second argument == third argument foundString = "NOT_FOUND" referenceColumn = getColumn(reference) replyColumn = getColumn(reply) openRead() # skip the top-most line headerLine = @file.gets begin thisLine = @file.gets thisTry = getCell(thisLine,referenceColumn) thisTry = thisTry.strip if ( thisTry.eql?(referenceItem) ) foundString = getCell(thisLine,replyColumn) end end while ( thisLine != nil ) foundString = foundString.chomp.strip return foundString end def makeBufferFileName #@bufferFileName = fullName + "_buff" @bufferFileName = getName + "_buff" end def getBufferFileName return(@bufferFileName) end def openBufferRead makeBufferFileName @bufferFile = File.open @bufferFileName,"r" if @bufferFile == nil print "\nERROR: Can't open buffer file for reading." exit end return end def openBufferWrite makeBufferFileName @bufferFile = File.open @bufferFileName,"w" if @bufferFile == nil print "\nERROR: Can't open buffer file for writing." exit end return end def closeBuffer @bufferFile.close return end def modify( destination, reference, referenceItem, newValue ) destinationColumn = getColumn(destination) referenceColumn = getColumn(reference) maxColumns = columnCount - 1 found = 0 first = 0 openBufferWrite openRead # skip the top-most line headerLine = @file.gets @bufferFile.puts(headerLine) thisLine = "DUMMY_VALUE" begin thisLine = @file.gets if ( thisLine != nil ) thisList = thisLine.strip.split(",") thisTry = thisList[referenceColumn] if ( thisTry.eql?(referenceItem) ) oldValue = getCell(thisLine,destinationColumn); found = 1 #print "\n\nfound ",thisTry, " in the ",reference," column" #print "\nreplacing ",oldValue," with ",newValue," in the ",destination," column" newList = thisList newList[destinationColumn] = newValue newString = newList.join(",") @bufferFile.puts(newString) found = 2 first = 1 end # of "FOUND" section if ( found == 0 ) @bufferFile.puts(thisLine) end # of NOT FOUND SECTION if ( found == 2 ) if ( first != 1 ) if ( thisLine != nil ) @bufferFile.puts(thisLine) end end first = 0 end # of FOUND == 2 section end # of thisLine != nil decision delimiter end while ( thisLine != nil ) close closeBuffer # Disable here to avoid overwriting the file during debug doTheBufferring return end def doTheBufferring openWrite openBufferRead begin thisLine = @bufferFile.gets if ( thisLine != nil ) @file.puts(thisLine) end end while ( thisLine != nil ) close closeBuffer end end # of class CsvFile
true
5770a25fb95da7cf2d9d71530244a4e0bc7eb229
Ruby
techiela/timecard.rb
/timecard.rb
UTF-8
3,095
3.203125
3
[]
no_license
require 'win32/eventlog' require 'date' require 'rubygems' require 'active_support/time' include Win32 class Timecard # # コンストラクタ # def initialize self.initializeEventLogContainer end # # イベントログ格納配列を初期化する # def initializeEventLogContainer @result = {} today = Date.today; # 先月の1日から今月の末日まで (today.months_ago(1).beginning_of_month..today.end_of_month).each do |day| @result[day.strftime('%Y-%m-%d')] = [] end end # # 起動メソッド # def main self.read self.buffer self.put end # # windowsのイベントログ(system)を読み込む # def read prevMonth = Date.today.months_ago(1).month currentMonth = Date.today.month # systemログを開く handle = EventLog.open('system') i = 0 # 直近の10000行を読み込むようにオフセットを計算する handle.read(EventLog::SEQUENTIAL_READ | EventLog::BACKWARDS_READ) do |log| if 10000 <= i += 1 break end # 先月・今月のデータのみを処理対象とする if log.time_written.month != currentMonth && log.time_written.month != prevMonth next end @result[log.time_written.strftime('%Y-%m-%d')] .push(log.time_written.strftime('%Y-%m-%d %H:%M')) end handle.close end # # 計算結果をバッファリングする # def buffer @buffer = "date\tstartTime\tendTime\trest\tactualWorkedHours\n" @result.each do |key, value| # イベントのない日をスキップ if value.length == 0 @buffer += sprintf("%s\n", key) next end # PC起動時刻を取得 boot = self.round(value.min) # PC起動時刻を09:30始業に合わせる if boot.strftime('%H%M') < '0930' boot = DateTime.parse(boot.strftime('%Y-%m-%d ') + '09:30'); end # PCシャットダウン(≒その日の最終イベント)時刻取得 shutdown = self.round(value.max) # 実働時間計算 diff = (((shutdown - boot) * 24 * 60).to_i); # diff minutes # 休憩時間 rest = 1 if '1400' <= boot.strftime('%H%M') || shutdown.strftime('%H%M') <= '1400' # 午後休 or 午後出社 rest = 0 end # 出力バッファに1行追加 @buffer += sprintf("%s\t%s\t%s\t%d:00\t%d.%02d\n", key, boot.strftime('%H:%M'), shutdown.strftime('%H:%M'), rest, diff / 60 - rest, diff % 60 / 15 * 25) end end # # 時刻を15分刻みにして返す(時刻の分のところを 00, 15, 30, 45 のみにする) # def round(value) d = DateTime.parse(value) odd = d.min % 15 if odd <= 7 return d - Rational(odd, 24 * 60) else return d + Rational(15 - odd, 24 * 60) end end # # 計算結果を出力する # def put print @buffer File.write('timecard.tsv', @buffer) end end # run timecard = Timecard.new timecard.main
true
ee13d508d251951786851d025db4b9d249a845ce
Ruby
deirdrehyde/W2D3
/poker/spec/card_spec.rb
UTF-8
324
2.6875
3
[]
no_license
require 'rspec' require_relative '../lib/card' describe Card do describe "#initialize" do subject(:card) {Card.new(:heart, 8)} it "establishes a value for the card" do expect(card.value).to eq(8) end it "establishes a suit for the card" do expect(card.suit).to eq(:heart) end end end
true
31ff99f14952c25a35f3c5fbf7edc008b9473df8
Ruby
danakatz/level_up_exercises
/data_science/spec/lib/data_calculator_spec.rb
UTF-8
858
2.734375
3
[ "MIT" ]
permissive
require "spec_helper" require "data_calculator" describe DataCalculator do it "calculates the conversion rate for each cohort" do reader = DataReader.new("data/test_data.json") calc = DataCalculator.new(reader) expect(calc.conversion_rate("A")).to equal(2 / 24.to_f) expect(calc.conversion_rate("B")).to equal(12 / 36.to_f) end it "calculates the confidence interval for each cohort" do reader = DataReader.new("data/test_data.json") calc = DataCalculator.new(reader) expect(calc.error_margin("A")).to be_within(0.005).of(0.1132) expect(calc.error_margin("B")).to be_within(0.005).of(0.1562) end it "uses a Chi-square test to determine confidence level" do reader = DataReader.new("data/test_data.json") calc = DataCalculator.new(reader) expect(calc.confidence).to be_within(0.001).of(0.975) end end
true
dd71baf7f3d78bda31731c1971a50b9f9d5c6526
Ruby
betodt/RubyHW
/HW/albertodiaztostado-278-5pm-assignment3/q4.rb
UTF-8
555
3.734375
4
[]
no_license
#!/usr/bin/ruby # Alberto Diaz-Tostado # COEN 278 # Assignment 3 # Question 4 class Array def collect i = 0 newAry = [] while i < length #push value returned from block into new array newAry.push(yield(self[i])) i += 1 end return newAry end def collect! i = 0 while i < length #assign value returned from block into current index self[i] = yield(self[i]) i += 1 end return self end end a = [1,2,3,4,5] print a.collect{|x| x*x} puts print a puts print a.collect!{|x| x*x} puts print a puts
true
f9fbdcf2e1bf5facc5f8744a7af7a0cb4a902b9c
Ruby
beingy/daily-recipe-cli-gem
/lib/daily_recipe/Recipe.rb
UTF-8
1,218
2.859375
3
[ "MIT" ]
permissive
class DailyRecipe::Recipe attr_accessor :name, :cook_time, :rating, :reviews, :url def self.today self.scrape_food_network end # def self.scrape_recipes # self.scrape_food_network # end def self.scrape_food_network recipes = [] doc = Nokogiri::HTML(open("http://www.foodnetwork.com/recipes/photos/recipe-of-the-day-what-to-cook-now.html")) doc.search(".feed li").each do |x| #binding.pry y = self.new y.name = x.search("h6 a").text y.cook_time = x.search("dd").text y.url = x.search(".community-rating-stars").attribute("href").value y.rating = " 5/7 " recipes << y end recipes end def self.scrape_full_recipe(the_recipe) doc = Nokogiri::HTML(open("http://www.foodnetwork.com"+the_recipe.url)) ingredients = doc.search("div.ingredients li") puts "" puts "Ingredients" ingredients.each do |ingredient| puts ingredient.text end cooking_instructions = doc.search("div.directions li") cooking_instructions.each do |instruction| puts "" puts instruction.text end #ingredients.each {|ingredient| puts ingredient} #cooking_instructions.each {|p| puts p} end end
true
5c0dcaf432caa159d40f4fb5fe4817e23791ce5f
Ruby
Alexis-Trainee/ruby
/each_array.rb
UTF-8
108
2.984375
3
[ "MIT" ]
permissive
names = ['Joãozinho', 'Manoel', 'Juca'] name = 'leonardo' names.each do |name| puts name end puts name
true
3e91b770e5385491d35181d7b81f8786a15f7523
Ruby
Nikos4Life/Prework-Ruby
/copy_name.txt
UTF-8
610
3.609375
4
[]
no_license
#this is a comment puts "I" puts "like" puts "pie." print "Cookies" print "are" print "good" print "too." operation_result = 12 * 34 puts "Operation result is " puts operation_result a_string = "This is a String" another_string = 'This is also a String' multiline_string = """ A long time ago in a galaxy far, far away... It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. """ puts "Hello\nworld" puts 'Hello\nworld' name = "Rafael" puts "Hi #{name}" puts "What's your name?" name = gets.chomp puts "Hello, #{name}."
true
13055498715f3a696af9a9e4cde7a904f95aec46
Ruby
shiado/Project-2-Muse
/db/seeds.rb
UTF-8
1,820
2.59375
3
[ "MIT" ]
permissive
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) [ { title: "How to be a millionaire", content: "If I charge my student 1 dollar for every mistake made, I might be rich!", user_id: 1, }, { title: "Buildings", content: "Why are buildings called buildings if they are already built?", user_id: 1, }, { title: "Jeremiah's famous quote", content: "Generalisation is a form of specialisation", user_id: 1, }, { title: "Naturalism", content: "Being natural is not a statement, it is the closest I can get to being myself", user_id: 2, }, { title: "Tinder Musings", content: "I wish that Tinder has a scheduler so that I can manage my dates with all the girls", user_id: 2, }, { title: "Extrovert", content: "I'm a real extrovert but when I am around someone new, I am super shy", user_id: 3, }, ].each do |post| Post.create(post) end [ { email:"[email protected]", username:"shiado", usertag: "I live in my head", password:"password1", password_confirmation:"password1", avatar_file_name:"shiado.jpg", }, { email:"[email protected]", username:"Hakim", usertag: "Swipe Right", password:"password2", password_confirmation:"password2", avatar_file_name:"user2.jpg", }, { email:"[email protected]", username:"Shyboy87", usertag: "I am shy", password:"password3", password_confirmation:"password3", avatar_file_name:"user3.jpg", }, ].each do |user| User.create(user) end
true
573074dc51d715c33abadddefc281042b39c7177
Ruby
Thomascountz/odin_projects
/caeser_cypher/lib/caeser_cypher.rb
UTF-8
598
3.234375
3
[]
no_license
SMALL_Z = 122 BIG_Z = 90 CHRS_IN_ALPHABET = 26 def c_cypher(args = {}) string = args.fetch(:string, nil) index = args.fetch(:index, nil) string = string.split('').map! do |character| if character =~ /[a-zA-z]/ if character =~ /[a-z]/ && character.ord + index > SMALL_Z ((character.ord + index) - CHRS_IN_ALPHABET).chr elsif character =~ /[A-Z]/ && character.ord + index > BIG_Z ((character.ord + index) - CHRS_IN_ALPHABET).chr else (character.ord + index).chr end else character end end string.join end
true
f2406969d26ca177ba6f8a5ce0203459afe47fa5
Ruby
huyserp/Advanced_Ruby_Building_Blocks
/bubble_sort.rb
UTF-8
1,264
3.796875
4
[]
no_license
def bubble_sort(array) shifting = true while shifting shift_count = 0 working_counter = 0 i = 0 while i < (array.length - 1) if array[i] > array[(i + 1)] array[i], array[(i + 1)] = array[(i + 1)], array[i] working_counter += 1 end i += 1 end if shift_count != working_counter shift_count = working_counter i = 0 else shifting = false end end return array end def bubble_sort_by(array) shifting = true while shifting shift_count = 0 working_counter = 0 i = 0 while i < (array.length - 1) if yield(array[i], array[(i + 1)]) > 0 array[i], array[(i + 1)] = array[(i + 1)], array[i] working_counter += 1 end i += 1 end if shift_count != working_counter shift_count = working_counter i = 0 else shifting = false end end return array end puts bubble_sort([22,10,0,12,2,1,7,150,4,3,78,2,0,2]) puts bubble_sort_by(["bonjour","hola","hi","hello","hey"]) { |left,right| left.length - right.length }
true
7cfe894f0bebb0bc6f8c4b65a4f21a087b2ffe20
Ruby
nyc-fiery-skippers-2016/flash-and-dash-cards
/db/seeds.rb
UTF-8
1,098
2.9375
3
[ "MIT" ]
permissive
Card.delete_all card_content = [{question: 'What ended in the year 1919?', answer: '1918', deck_id: 1}, {question: 'It goes all over the world, but always stays in a corner. What is that?', answer: 'stamp', deck_id: 1}, {question: 'It goes up and comes down, but never move. What it is?', answer:'staircase',deck_id: 1}, {question: 'I have four legs – but I can’t walk. What Am I?', answer: 'chair', deck_id: 1}, {question: 'There is a head and there is a tail! But no body – what is it?', answer: 'coin', deck_id: 1} ] Deck.create!(title: 'Jokes') Card.create!(card_content) card_content_2 = [{question: 'Who is the Chancellor of Germany?', answer: 'Angela Merkel', deck_id: 2}, {question: 'Who is the Prime Minister of Canada?', answer: 'Justin Trudeau', deck_id: 2}, {question: 'Who is the President of South Africa?', answer: 'Jacob Zuma', deck_id: 2}, {question: 'Who is the Prime Minister of the United Kingdom?', answer: 'David Cameron', deck_id: 2}, {question: 'Who is the Prime Minister of New Zealand?', answer: 'John Key', deck_id: 2}] Deck.create!(title: 'World Leaders') Card.create!(card_content_2)
true
f09969799f38a32c9424dc7002d27470cb00a4d7
Ruby
sarahseewhy/student-directory_beta
/exercise6.rb
UTF-8
2,737
4
4
[]
no_license
# Adding more information #You can add more information info about students in the 'students' array or you can ask user for input # students = => [ # {:name => "Mario Gintili", :cohort => :February, :hobby => :coding} # {:name => "Mikhail Dubov", :cohort => :February, :hobby => :coding} # {:name => "Karolis Noreika", :cohort => :February, :hobby => :coding} # {:name => "Michael Sidon", :cohort => :February, :hobby => :coding} # {:name => "Charles De Barros", :cohort => :February, :hobby => :coding} # {:name => "Ruslan Vikhor", :cohort => :February, :hobby => :coding} # {:name => "Toby Retallick", :cohort => :February, :hobby => :coding} # {:name => "Mark Mekhaiel", :cohort => :February, :hobby => :coding} # {:name => "Sarah Young", :cohort => :February, :hobby => :coding} # {:name => "Hannah Wight", :cohort => :February, :hobby => :coding} # {:name => "Khushkaran Singh", :cohort => :February, :hobby => :coding} # {:name => "Rick Brunstedt", :cohort => :February, :hobby => :coding} # {:name => "Manjit Singh", :cohort => :February, :hobby => :coding} # {:name => "Alex Gaudiosi", :cohort => :February, :hobby => :coding} # {:name => "Ross Hepburn", :cohort => :February, :hobby => :coding} # {:name => "Natascia Marchese", :cohort => :February, :hobby => :coding} # {:name => "Tiffanie Chia", :cohort => :February, :hobby => :coding} # {:name => "Matthew Thomas", :cohort => :February, :hobby => :coding} # {:name => "Freddy McGroarty", :cohort => :February, :hobby => :coding} # {:name => "Tyler Rollins", :cohort => :February, :hobby => :coding} # {:name => "Richard Curteis", :cohort => :February, :hobby => :coding} # {:name => "Anna Yanova", :cohort => :February, :hobby => :coding} # {:name => "Andrew Cumine", :cohort => :Februar, :hobby =>:coding} # ] def print_header puts "The students of my cohort at Makers Academy" puts "-----------" end def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice" # create an empty array students = [] # get the first name name = gets.chomp # while the name is not empty, repeat this code while !name.empty? do # add the student hash to the array students << {:name => name, :cohort => :February} # ask about students' hobbies puts "What does ze like to do?" # get their hobby hobby = gets.chomp # ask about students' home country puts "Where is ze from?" country = gets.chomp puts "Now we have #{students.length} students" # get another name from the user name = gets.chomp end # return the array of students students end # def print(students) # a = 0 # while a < students.length # puts "#{students[a][:name]} (#{students[a][:cohort]} cohort)" # a += 1 # end # end def print_footer(names) puts "Overall, we have #{names.length} great students" end print_header students = input_students # print(students) print_footer(students)
true
143fc9f69eb25187aa02f53dbd3e22802a99289b
Ruby
LeftoverCurry/Hangman
/lib/game_data.rb
UTF-8
1,613
3.203125
3
[]
no_license
# frozen_string_literal: true require 'json' require './lib/magic_word.rb' # contains information to run or save a game. class GameData attr_accessor :user_name, :chosen_letters, :guesses_remaining attr_accessor :letters_left_to_guess, :randomly_picked_word def initialize( user_name, chosen_letters = [], guesses_remaining = 5, letters_left_to_guess = false, randomly_picked_word = [] ) @user_name = user_name @chosen_letters = chosen_letters @guesses_remaining = guesses_remaining @letters_left_to_guess = letters_left_to_guess @randomly_picked_word = randomly_picked_word create_magic_word(randomly_picked_word) end def create_magic_word(randomly_picked_word) return unless randomly_picked_word == [] magic_word = MagicWord.new @letters_left_to_guess = magic_word.data @randomly_picked_word = magic_word.constant end def save info = { user_name: @user_name, chosen_letters: @chosen_letters, guesses_remaining: @guesses_remaining, letters_left_to_guess: @letters_left_to_guess, randomly_picked_word: @randomly_picked_word } filename = "./saved_games/#{@user_name}.json" File.open(filename, 'w') do |file| file.puts info.to_json end end def self.pull(user_name) saved_data = JSON.parse(File.read("./saved_games/#{user_name}.json")) new( saved_data['user_name'], saved_data['chosen_letters'], saved_data['guesses_remaining'], saved_data['letters_left_to_guess'], saved_data['randomly_picked_word'] ) end end
true
8f989efa9e9caa71236f4984ad944a388f44e59d
Ruby
alf-tool/alf-core
/lib/alf/engine/materialize/array.rb
UTF-8
2,103
3.25
3
[ "MIT" ]
permissive
module Alf module Engine # # Provides in-memory materialization through a ruby Array. # # This class acts as a Cog, that it, it is an enumerable of tuples. An # optional ordering can be passed at construction. # # Materialization occurs at prepare time, with auto-prepare on first # access. # # Example: # # rel = [ # {:name => "Jones", :city => "London"}, # {:name => "Smith", :city => "Paris"}, # {:name => "Blake", :city => "London"} # ] # # Materialize::Array.new(rel).to_a # # => same as rel, in same order as the source # # Materialize::Array.new(rel, Ordering[[:name, :asc]]).to_a # # => [ # {:name => "Blake", :city => "London"}, # {:name => "Jones", :city => "London"}, # {:name => "Smith", :city => "Paris"} # ] # class Materialize::Array include Materialize include Cog # @return [Enumerable] The operand attr_reader :operand # @return [Ordering] Ordering to ensure (optional) attr_reader :ordering # Creates a Materialize::Array instance def initialize(operand, ordering = nil, expr = nil, compiler = nil) super(expr, compiler) @operand = operand @ordering = ordering @materialized = nil end # (see Cog#each) def _each(&block) materialized.each(&block) end # (see Cog#prepare) # # Prepare through materialization of the operand as an ordered array def prepare @materialized ||= begin arr = operand.to_a arr.sort!(&ordering.sorter) if ordering arr end end # (see Cog#free) # # Frees the materizalied hash def clean @materialized = nil end private # @return [Array] the materialized array def materialized prepare @materialized end end # class Materialize::Array end # module Engine end # module Alf
true
4f65ab308c3db35428d4a2d995404cfa53a3b974
Ruby
jodar/exercicios_algoritmos
/exercicios_arthur/folha_14/ex_14_15-1.rb
UTF-8
170
3.203125
3
[]
no_license
a = [21, 12, 1, 0, 14, -4, -5, 42, 23, 32] b = [] puts a.inspect a.reverse_each do |item| b.push << item end a.clear b.each do |item| a.push << item end print a
true
6346cccc34b8d7826dd9e970213faa0a37728129
Ruby
afinebojangle/clickametrics
/db/seeds.rb
UTF-8
637
2.640625
3
[]
no_license
require 'faker' 5.times do user = User.new( email: Faker::Internet.email, password: Faker::Lorem.characters(10)) user.save! end users = User.all 50.times do Website.create!( user: users.sample, url: Faker::Internet.url ) end websites = Website.all 100.times do website = websites.sample Event.create!( website_id: website.id, name: Faker::Lorem.word ) end user = User.first user.update_attributes!( email: '[email protected]', password: 'helloworld' ) puts "Seed finished" puts "#{User.count} users created" puts "#{Website.count} websites created" puts "#{Event.count} events created"
true
950289963457655cd5590bf22745f376bada106a
Ruby
panther99/srbot
/lib/core.rb
UTF-8
1,789
3.140625
3
[]
no_license
require 'pretty-xml' include PrettyXML require_relative "helpers.rb" class Bot # Creates new AIML constructor with defined bot name and version # # @param name [String] name of AIML document # @param version [String] version of AIML used in document def initialize(name, version="2.0") @name = name @content = @content.to_s + "<aiml version=\"#{version}\">" @debug = false @pretty = true end # Defines category with pattern and template in it # # @param hash [Hash] content for pattern and template (pattern => template) def on(hash) if hash.is_a? Hash @content += "<category><pattern>#{hash.keys[0].upcase}</pattern><template>#{hash.values[0]}</template></category>" else raise "on function needs to have hash as parameter" end end # Defines options for current bot # # @note Debug option can be changed manually throughout the program (see {#verbose_on} and {#verbose_off})! # @param conf [Hash] options for current bot def options(conf = { :debug => false, :pretty => true }) @debug = conf[:debug] @pretty = conf[:pretty] end # Builds current AIML document def build if [email protected]? @content += "</aiml>" else raise "build function needs to be called when specification is finished" end end # Turns on debugging def verbose_on @debug = true end # Turns off debugging def verbose_off @debug = false end # Returns the name of AIML document # # @return [String] name of current AIML document def get_name return @name end # Returns the AIML content of the current instance # # @note If pretty option is turned on returned code will be formatted # @return [String] content of the current instance def get_content if @pretty return write @content else return @content end end end
true
c3b5e75d350d13c0e349856ea416cd41059220d6
Ruby
4amic/Anagram_Generator
/app/models/word.rb
UTF-8
1,032
3.375
3
[]
no_license
class Word < ActiveRecord::Base before_save :add_letters, :downcase validates_presence_of :text def add_letters characters = self.text.chars alphabetized_characters = characters.sort self.letters = alphabetized_characters.join end def downcase self.text.downcase! end def self.find_anagrams(word) anagrams = [] final_list = [] letters = word.split('') for letter in letters do second_two = reverse_letters(letters.last(2)) letters = [letters[0], second_two].flatten! anagrams << letters.join unless letters.join == word letters[0], letters[1] = letters[1], letters[0] anagrams << letters.join unless letters.join == word end anagrams.each do |potential_word| if Word.find_by_text(potential_word).present? final_list << potential_word end end final_list.uniq end def self.reverse_letters(word) reversed = Array.new(word.length) word.each_with_index {|letter, index| reversed[word.length - index - 1] = letter} reversed end end
true
506701aec6d8746a9b2a80d507ce3a90fed82a0b
Ruby
naridas/airport_challenge
/spec/airport_spec.rb
UTF-8
1,251
2.765625
3
[]
no_license
require 'airport' describe Airport do let(:plane){ double :plane } let(:weather){double :weather} #let(:good_weather){ double :weather, stormy?: false} #let(:bad_weather){ double :weather, stormy?: true } subject(:airport){ described_class.new(weather, capacity = rand(100))} it 'landing plane' do allow(weather).to receive(:stormy?).and_return(false) expect(airport.land(plane)).to eq [plane] end it 'plane taking off' do allow(weather).to receive(:stormy?).and_return(false) airport.land(plane) expect(airport.take_off(plane)).to eq plane end it 'prevent take off due to storm' do allow(weather).to receive(:stormy?).and_return(false) airport.land(plane) allow(weather).to receive(:stormy?).and_return(true) expect{airport.take_off(plane)}.to raise_error 'There is a storm occuring at the airport' end it 'prevent landing due to storm' do allow(weather).to receive(:stormy?).and_return(true) expect{airport.land(plane)}.to raise_error 'There is a storm occuring at the airport' end it 'prevent landing when airport is full' do allow(weather).to receive(:stormy?).and_return(false) airport.capacity.times { airport.land(plane)} expect { subject.land(plane) }.to raise_error 'Airport full' end end
true
64a78adde1a1b1d6e5607a425a59033d5ed0e02b
Ruby
sveredyuk/kottans_hometasks-1
/1/task_1_simple_calculator.rb
UTF-8
890
3.984375
4
[]
no_license
class Calculator def initialize @a = get_operand 'A' @b = get_operand 'B' @operation = get_operation end def calculate result = @a.public_send(@operation, @b) result.finite? ? result : "Division by zero? What a pity!" end private def get_operand operand print "Please, enter #{operand}: " begin input = Float gets.chomp rescue ArgumentError => e puts "Sorry, incorrect input. Try again." get_operand operand end end def get_operation print "What would you like to do with them (+, -, *, /) ?: " operation = valid_operation? gets.chomp end def valid_operation? operation if %w{+ - * /}.include? operation operation else puts "I have no idea how to handle this :( Give me something else." get_operation end end end calc = Calculator.new puts "Result: #{calc.calculate}"
true
b06184bac63ee983b17e16492445be04cee51965
Ruby
mmdotz/tictactoe
/spec/gametestindex.rb
UTF-8
6,060
3.796875
4
[]
no_license
class Player attr_reader :choice_array, :choice, :print_X, :build_computer_choice_array def initialize @choice_array = [] #didn't need @choice here because we assigned it when first used @win = false end def build_choice_array #human choice array @choice_array << @choice end def build_computer_choice_array @choice_array << @random_choice end def choose_b_position puts "Please choose a number:" @choice = gets.chomp.to_i end def computer_choice(x) @random_choice = x #choice = computer.random_choice end def random_choice @random_choice end def win @win end def check_win_horiz if @choice_array.include?(0)&& @choice_array.include?(1)&& @choice_array.include?(2)|| @choice_array.include?(3)&& @choice_array.include?(4)&& @choice_array.include?(5)|| @choice_array.include?(6)&& @choice_array.include?(7)&& @choice_array.include?(8) @win = true end end def check_win_vert if @choice_array.include?(0)&& @choice_array.include?(3)&& @choice_array.include?(6)|| @choice_array.include?(1)&& @choice_array.include?(4)&& @choice_array.include?(7)|| @choice_array.include?(2)&& @choice_array.include?(5)&& @choice_array.include?(8) @win = true end end def check_win_diag if @choice_array.include?(0)&& @choice_array.include?(4)&& @choice_array.include?(8)|| @choice_array.include?(2)&& @choice_array.include?(4)&& @choice_array.include?(6) @win = true end end end class Board attr_reader :board_display, :spaces, :outcome1, :outcome2, :outcome3, :outcome4, :outcome5, :outcome6, :outcome7, :outcome8 # => nil def initialize @spaces = [0,1,2,3,4,5,6,7,8] @static_spaces = [0,1,2,3,4,5,6,7,8] # @outcome1 = [0,1,2] # @outcome2 = [3,4,5] # @outcome3 = [6,7,8] # @outcome4 = [0,3,6] # @outcome5 = [1,4,7] # @outcome6 = [2,5,8] # @outcome7 = [0,4,8] # @outcome8 = [2,4,6] end def static_spaces(x) @static_spaces = x end def static_spaces @static_spaces end def board_display #credit ryan yep puts "------------------------------------------------" puts "| | | |" puts "| | | |" puts "| #{@static_spaces[0]} | #{@static_spaces[1]} | #{@static_spaces[2]} |" puts "| | | |" puts "| | | |" puts "-----------------------------------------------" puts "| | | |" puts "| | | |" puts "| #{@static_spaces[3]} | #{@static_spaces[4]} | #{@static_spaces[5]} |" puts "| | | |" puts "| | | |" puts "-----------------------------------------------" puts "| | | |" puts "| | | |" puts "| #{@static_spaces[6]} | #{@static_spaces[7]} | #{@static_spaces[8]} |" puts "| | | |" puts "| | | |" puts "-----------------------------------------------" end end class Game def run_game #def decide_players throws an error because can't instatiate new players inside method? # def decide_players # puts "Do you want to play [P]layer vs. Computer OR [C]omputer vs. Computer?" # game_type = gets.chomp.upcase # if game_type == "C" #create 2 computer players # computer_1 = Player.new # computer_2 = Player.new # elsif game_type == "P" #create human and computer players # human = Player.new # computer_1 = Player.new # else # puts "Please choose only C or P" # end # end human = Player.new #create player computer = Player.new board = Board.new #created a new board to play on # until human.choice_array.length == 4 human.choose_b_position #ask and gets if board.spaces.include?(human.choice) human.build_choice_array board.spaces.delete(human.choice) #print X to board board.static_spaces.each { |n| board.static_spaces[human.choice] = "X" } #computer's turn computer.computer_choice(board.spaces.sample) computer.build_computer_choice_array board.spaces.delete(computer.random_choice) board.static_spaces.each { |n| board.static_spaces[computer.random_choice] = "O" } puts "Human choices: #{human.choice_array}." #show choices puts "Computer's choices: #{computer.choice_array}." puts "Available spaces #{board.spaces}" board.board_display #show board with new X else puts "Not a valid choice. Pick only from available spaces :#{board.spaces}." end end if human.check_win_diag == true puts "You win!" elsif computer.check_win_diag == true puts "Computer wins!" elsif human.check_win_vert == true puts "You win!" elsif computer.check_win_vert == true puts "Computer wins!" elsif human.check_win_horiz == true puts "You win!" elsif computer.check_win_horiz == true puts "Computer wins!" else "Draw!" end # if board.static_spaces.include?(human.choice) # board.static_spaces((human.choice).replace("X")) # else # puts "Not a valid choice, please choose from board numbers" # end #print completed game end end
true
9df2eb8d30eb4138d2b16b24940a225a287b04f2
Ruby
andersonrodriguesdelima/changedate
/app/models/change_date.rb
UTF-8
2,842
3.125
3
[]
no_license
class ChangeDate < ApplicationRecord def self.change_date(date, operacao, minutos) return ArgumentError, "Data não pode ser vazia" if date.to_s.empty? return ArgumentError, "Operação não pode ser vazia" if operacao.to_s.empty? return ArgumentError, "Operação inválida. Somente são permitidas as operações + e -" if !(["+", "-"].include? operacao) return ArgumentError, "Minutos não pode ser vazio" if minutos.to_s.empty? # Separando string para determinar quem é dia, mes, ano, hora, minuto dia_atual = date.split("T").first.split("-").last.to_i mes_atual = date.split("T").first.split("-").second.to_i ano_atual = date.split("T").first.split("-").first.to_i horas_atual = date.split("T").last.split(":").first#.to_i minutos_atual = date.split("T").last.split(":").last#.to_i horas = minutos.to_f / 60 minutos = minutos.to_f % 60 dias = minutos.to_i / 24 dias_final = dia_atual mes_final = mes_atual ano_final = ano_atual horas_final = horas_atual if operacao.eql? "+" minutos_final = minutos_atual.to_i + minutos.to_i (1..horas.to_i).each do |h| horas_final = horas_final.to_i + 1 if horas_final == 24 dias_final += 1 horas_final = horas_final - 24 end if dias_final > self.ultimo_dia_mes(mes_atual) dias_final = 1 mes_final += 1 end if mes_final > 12 ano_final += 1 mes_final = 1 end end end if operacao.eql? "-" minutos_final = minutos_atual.to_i (1..minutos.to_i).each do |m| minutos_final = minutos_final.to_i - 1 if minutos_final < 0 horas_final = horas_final.to_i - 1 minutos_final = 59 end end (1..horas.to_i).each do |h| horas_final = horas_final.to_i - 1 if horas_final < 0 horas_final = horas_final + 24 dias_final -= 1 end if dias_final < 0 mes_final = mes_final - 1 if mes_final == 0 ano_final -= 1 mes_final = 12 end dias_final = self.ultimo_dia_mes(mes_final) end end end if horas_final.to_s.size.eql? 1 horas_final = "0#{horas_final}" end if minutos_final.to_s.size.eql? 1 minutos_final = "0#{minutos_final}" end if minutos_final.to_s.size.eql? 0 minutos_final = "00" end return "#{dias_final}/#{mes_final}/#{ano_final} #{horas_final}:#{minutos_final}" end def self.ultimo_dia_mes(mes) meses_30_dias = [4, 6, 9, 11] meses_31_dias = [1, 3, 5, 7, 8, 10, 12] if meses_30_dias.include?(mes) return 30 end if meses_31_dias.include?(mes) return 31 end return 28 end end
true
f0cc9ff0bd483940c90f54a344699c8f0166311e
Ruby
Rooted1/Pizza_Gallery
/lib/p_buy_view.rb
UTF-8
4,453
3.3125
3
[]
no_license
require_relative './p_readyforcheckout.rb' require 'pry' def create_order(pizza) users_pizza = Pizza.find_by(pizza_name: pizza) current_user = User.find_by(name: $name_input) users_cart = Cart.find_or_create_by(user_id: current_user.id) users_order = Order.create(pizza_id: users_pizza.id, cart_id: users_cart.id) end def find_user_cart(name) current_user = User.find_by(name: name) users_cart = Cart.find_or_create_by(user_id: current_user.id) users_cart end def cart_orders(cart) cart_items = [] cart.orders.each do |order| cart_items << order.pizza.pizza_name end end def get_pizza_description(name) pizz = Pizza.find_by(pizza_name: name) pizz.description end def buy_pizza_or_view_cart user_choice = $prompt.select("What do you want to do?", ["Buy a pizza","View my cart"]) if user_choice == "Buy a pizza" pizza_choice = $prompt.select("Select a pizza from the list", ["Cheese","Hawaiian","Pepperoni","Supreme Pizza","Greek Pizza","Vegeterian Pizza"]) case pizza_choice when "Cheese" create_order("Cheese") when "Hawaiian" create_order("Hawaiian") when "Pepperoni" create_order("Pepperoni") when "Supreme Pizza" create_order("Supreme Pizza") when "Greek Pizza" create_order("Greek Pizza") when "Vegeterian Pizza" create_order("Vegeterian Pizza") end end users_own_cart = find_user_cart($name_input) all_cart_orders = cart_orders(users_own_cart) cart_total = 0 cart_items = [] all_cart_orders.each do |order| cart_items << (order.pizza.pizza_name) cart_total += order.pizza.price end if users_own_cart == nil puts "Your cart is empty" else if cart_items.length == 0 puts "Your cart is empty" else puts "Items currently in your cart: #{cart_items.join(", ")}" puts "Your total is: #{cart_total}" end end cart_choice = $prompt.select("What would you like to do?", ["Remove items","View pizza menu","Ready_for_checkout"]) if cart_choice == "Remove items" if cart_items.length != 0 remove_choice = $prompt.select("What would you like to remove", cart_items) puts "Item removed" removed_pizza = all_cart_orders.select{|order| order.pizza.pizza_name == remove_choice}.shift remaining_order = all_cart_orders.reject{|order| order.pizza.pizza_name if order == removed_pizza} removed_pizza_price = removed_pizza.pizza.price cart_total -= removed_pizza_price cart_items = remaining_order.to_a.map{|order| order.pizza.pizza_name} removed_pizza.destroy buy_pizza_or_view_cart else puts "Nothing to remove" end elsif cart_choice == "View pizza menu" pizza_descript = $prompt.select("Select a pizza", ["Pepperoni","Hawaiian","Cheese","Supreme Pizza","Greek Pizza","Vegeterian Pizza"]) case pizza_descript when "Pepperoni" puts get_pizza_description("Pepperoni") buy_pizza_or_view_cart when "Hawaiian" puts get_pizza_description("Hawaiian") buy_pizza_or_view_cart when "Cheese" puts get_pizza_description("Cheese") buy_pizza_or_view_cart when "Supreme Pizza" puts get_pizza_description("Supreme Pizza") buy_pizza_or_view_cart when "Greek Pizza" puts get_pizza_description("Greek Pizza") buy_pizza_or_view_cart when "Vegeterian Pizza" puts get_pizza_description("Vegeterian Pizza") buy_pizza_or_view_cart end elsif cart_choice == "Ready_for_checkout" ready_for_checkout? user_choice = "done" end if user_choice == "View my cart" if users_own_cart == nil puts "Your cart is empty" else if cart_items.length == 0 puts "Your cart is empty" else puts "Items currently in your cart: #{cart_items.join(", ")}" puts "Your total is: #{cart_total}" binding.pry end end end end
true
438eb1ce6b133d88feb2ea8e9cd2c34eee62f617
Ruby
kssajith/nearby_parking
/lib/http_client.rb
UTF-8
189
2.640625
3
[ "MIT" ]
permissive
require 'net/http' class HttpClient attr_reader :client def initialize(client = Net::HTTP) @client = client end def get(uri) uri = URI(uri) client.get(uri) end end
true
a1eb83c597fea647a3d138df2584fafae57ba9c7
Ruby
Bayonnaise/Week-4-challenge
/Level1/spec/new_inject_spec.rb
UTF-8
1,681
3.21875
3
[]
no_license
require 'new_inject' describe Array do let(:ary) { [1,2,3,4,5] } context 'iteration approach' do it 'sums a simple array using iteration' do expect(ary.iteration_inject(0)).to eq 15 end it 'sums the same array with no starting value' do expect(ary.iteration_inject).to eq 15 end it 'accepts a starting value as an argument' do expect(ary.iteration_inject(5)).to eq 20 end it 'cannot accept three arguments' do expect { ary.iteration_inject(3,5,6) }.to raise_error end it 'raises error if arg2 is not a symbol' do expect { ary.iteration_inject(3,"z") }.to raise_error end it 'can can multiply as well' do expect(ary.iteration_inject(1, :*)).to eq 120 end it 'can add strings' do str_ary = ["hello", "darkness", "my", "old", "friend"] expect(str_ary.iteration_inject).to eq "hellodarknessmyoldfriend" end end context 'recursion approach' do it 'accepts a starting value as an argument' do expect(ary.recursion_inject(5)).to eq 20 end it 'sums a simple array using recursion' do expect(ary.recursion_inject(0)).to eq 15 end it 'sums the same array with no starting value' do expect(ary.recursion_inject).to eq 15 end it 'cannot accept three arguments' do expect { ary.recursion_inject(3,5,6) }.to raise_error end it 'raises error if arg2 is not a symbol' do expect { ary.recursion_inject(3,"z") }.to raise_error end it 'can can multiply as well' do expect(ary.recursion_inject(1, :*)).to eq 120 end it 'can add strings' do str_ary = ["hello", "darkness", "my", "old", "friend"] expect(str_ary.recursion_inject).to eq "hellodarknessmyoldfriend" end end end
true
a7bc1b80be0b10f1d39c8e23b0d6c88e5831816b
Ruby
JramR7/mock-nequi
/app/db_managers/transaction_manager.rb
UTF-8
1,900
2.84375
3
[]
no_license
require_relative 'helpers/validate_data' require_relative '../models/transaction' require_relative 'helpers/sql_query_executor' class TransactionManager include ValidateData include SqlQueryExecutor def insert(params) if valid_data?(params) if insert_execution('transactions', params) transaction_id = get_last_register_execution('transactions') params[:id] = transaction_id[0] Transaction.new(params) else false end else false end end def find(id) find_execution('transactions', id) Transaction.new end def get_all_transactions(account_id) individual_transactions = find_all_column_join_execution('individual_transaction', 'transaction', 'account_id', account_id) mutual_transactions_out = find_all_column_join_execution('mutual_transaction', 'transaction', 'origin_account_id', account_id) mutual_transactions_in = find_all_column_join_execution('mutual_transaction', 'transaction', 'final_account_id', account_id) data = { individual_transactions: individual_transactions, mutual_transactions_in: mutual_transactions_in, mutual_transactions_out: mutual_transactions_out } data end # UPDATE And DELETE builders need a dict with the columns and values, if empty value = nil def update(id, params) if valid_data?(params) update_execution('transactions', params, id) else print("ERROR: couldn't insert account data") end end def delete(id) delete_execution('transactions', id) end private def valid_data?(params) date_valid = params.key?(:date) ? datetime_validation(params[:date]) : true amount_valid = params.key?(:amount) ? numeric_validation(params[:amount]) : true if date_valid && amount_valid return true else return false end end end
true
1a2794802badb8537435d49b064eda647e127e9b
Ruby
momchenr/scratch
/app/helpers/users_helper.rb
UTF-8
435
2.578125
3
[]
no_license
module UsersHelper def location_display(user) return "---" if user.city.blank? && user.state.blank? return user.city.camelcase + ", " + user.state.upcase if user.state && user.city return user.state.upcase if user.state && user.city.blank? return user.city.camelcase if user.city && user.state.blank? end def phone_display(user) return "---" if user.phone.blank? return user.phone if user.phone end end
true
d745df2069c0bb78f7b7136393ffada34976dc92
Ruby
viniciustferreira/cv_mail
/spec/xml_spec.rb
UTF-8
918
2.578125
3
[]
no_license
require "./App/xml.rb" describe "Xml" do before(:all) do @xml = Xml.new("./Config/dados_email_teste.xml","./Config/data.xml","./Config/body.xml","./Config/signature_teste.xml") @data = { :domain => 'gmail.com', :user => 'viniciustferreira.affairs', :password => "S@ra5432Um", :smtp => 'smtp.gmail.com', :attachment =>"./Config/curriculum.pdf", } end describe "recovering data from xml file" do it "should give me email" do @xml.read_xml expect(@xml.email[0].text).to be_eql("[email protected]") end it "should return the quantity of the emails in the file" do expect(@xml.get_file_size).to be_equal(1) end it "should access the data file and get the data" do @xml.read_data_file expect(@xml.data).to be_eql(@data) end it "should give me the body" do @xml.read_body "teste" expect(@xml.body).to be_eql("teste de corpo#teste assinatura") end end end
true
bff798bbffc0cf2c46b85c25bfa725ef69075a94
Ruby
MihaiLiviuCojocar/unbeatable-tic-tac-toe
/features/step_definitions/web_steps.rb
UTF-8
1,996
2.671875
3
[]
no_license
Given(/^I am on the homepage$/) do visit '/' end Then(/^I should see "([^"]*)"$/) do |text| expect(page).to have_content text end When(/^I register$/) do fill_in 'player_name', with: 'Mihai' click_on 'Register' end Then(/^I should see a welcome message$/) do expect(page).to have_content "Welcome, Mihai!" end Then(/^I should be asked what kind of a game I want to play$/) do expect(page).to have_content "Choose between" expect(page).to have_link 'Human' expect(page).to have_link 'Computer' end Given(/^I am alredy registered$/) do steps %{ Given I am on the homepage And I register } end Given(/^I want to play against another human$/) do click_link 'Human' end Then(/^the second player should be asked to register$/) do expect(page).to have_content 'What is the name of the second player?' end Given(/^there are two players registered$/) do steps %{ Given I am alredy registered And I want to play against another human } fill_in "second_player_name", with: 'Roi' click_on 'Register' end Given(/^player one has cross as a marker$/) do expect(page).to have_content "Mihai's marker is X" end Given(/^player two has a zerro as a marker$/) do expect(page).to have_content "Roi's marker is O" end Given(/^there is a fresh game$/) do visit '/reset' end Given(/^we have a grid like this:$/) do |table| select('A', from: 'letter') select('1', from: 'number') click_on 'Move' select('B', from: 'letter') select('2', from: 'number') click_on 'Move' select('A', from: 'letter') select('2', from: 'number') click_on 'Move' select('C', from: 'letter') select('2', from: 'number') click_on 'Move' end When(/^player one places his marker at A(\d+)$/) do |coordinate| select('A', from: 'letter') select('3', from: 'number') click_on 'Move' end Then(/^player one wins$/) do expect(page).to have_content "Mihai wins!" end Then(/^I should have the option to reset$/) do expect(page).to have_link 'Reset' end
true
8c0d9054cc1372adf7ca084b8f71d256caf01c1c
Ruby
newtypeV2/ruby-collaborating-objects-lab-dc-web-051319
/lib/mp3_importer.rb
UTF-8
323
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MP3Importer attr_reader :path attr_accessor :songs def initialize(path) @path = path end def files fileArray=Dir[self.path+"/*.mp3"] songs = fileArray.collect do |songtitle| songtitle[21..] end end def import self.files.each {|x| Song.new_by_filename(x) } end end
true
90d82a8c3511f3a0650974e4cf96389607111259
Ruby
ysaito8015/ex_ruby
/ex1704.rb
UTF-8
488
3.421875
3
[]
no_license
# 配列にデータを作成 fruits = %W(apple banana cherry fig grape) # "sample4.txt" を書き込みモードで新規に作成 file = File.open("sample4.txt", "w:UTF-8") fruits.each do |fruit| file.puts fruit end # ファイルを閉じる file.close # "sample4.txt" を読込モードでオープンする file = open("sample4.txt", "r:UTF-8") # ファイルからデータをすべて読み込み、それを表示する print file.read # ファイルを閉じる file.close
true
a5bab8e48c4c85dd22b1c1f2529d58c9006188a8
Ruby
NJichev/ruby-homework
/tasks/05/sample_spec.rb
UTF-8
3,592
2.921875
3
[]
no_license
require 'rspec' require_relative 'solution' RSpec.describe DataModel do let(:user_model) do Class.new(DataModel) do attributes :first_name, :last_name data_store HashStore.new end end describe '.attributes' do it 'returns said attributes' do expect(user_model.attributes).to match_array [:first_name, :last_name] end end it 'creates attribute accessors' do record = user_model.new record.first_name = 'Pesho' record.last_name = 'Petrov' expect(record).to have_attributes first_name: 'Pesho', last_name: 'Petrov' end describe '#new' do it 'accepts hash for parameters' do record = user_model.new(first_name: 'Pesho', last_name: 'Petrov') expect(record).to have_attributes first_name: 'Pesho', last_name: 'Petrov' end it 'ignores unset attributes' do record = user_model.new(first_name: 'Pesho', last_name: 'Petrov', email: '[email protected]', password: '1234') expect(record).to have_attributes first_name: 'Pesho', last_name: 'Petrov' end it "sets default value to nil if not given" do record = user_model.new expect(record).to have_attributes first_name: nil, last_name: nil end end describe '.where' do it 'finds with one attribute' do user_model.new(first_name: 'Pesho', last_name: 'Petrov').save user_model.new(first_name: 'Pesho', last_name: 'Petrov').save user_model.new(first_name: 'Pesho', last_name: 'Petrov').save expect(user_model.where(first_name: 'Pesho', last_name: 'Petrov').count).to eq 3 end end describe '#id' do it 'returns nil if unpersisted object' do expect(user_model.new.id).to be nil end it 'returns id in store if saved' do expect(user_model.new.save.id).to eq 1 expect(user_model.new.save.id).to eq 2 expect(user_model.new.save.id).to eq 3 end end describe '#delete' do it "raises an exception if the record isn't persisted to the data store" do end end end RSpec.shared_examples_for 'a data store' do subject(:store) { described_class.new } describe '#create' do it 'saves a new record' do user = {id: 2, name: 'Pesho'} store.create(user) expect(store.find(id: 2)).to match_array [user] end end describe '#find' do it 'finds records' do user = {id: 1, name: 'Pesho'} admin = {id: 2, name: 'Gosho', admin: true} client = {id: 3, name: 'Pesho'} store.create(user) store.create(admin) store.create(client) expect(store.find(name: 'Pesho')).to match_array [user, client] end it 'returns an empty array if none are found' do expect(store.find(name: 'Pesho')).to match_array [] end end describe '#update' do it 'updates a record' do user = {id: 2, name: 'Gosho', email: '[email protected]'} store.create(user) new_attributes = {name: 'Pesho', email: '[email protected]'} store.update(2, new_attributes) expect(store.find(id: 2)).to match_array [new_attributes.merge({id: 2})] end end describe '#delete' do it 'deletes a record' do user = {id: 1, name: 'Pesho'} admin = {id: 2, name: 'Gosho', admin: true} client = {id: 3, name: 'Pesho'} store.create(user) store.create(admin) store.create(client) store.delete(name: 'Pesho') expect(store.find(name: 'Gosho')).to match_array [admin] end end end describe HashStore do it_behaves_like 'a data store' end describe ArrayStore do it_behaves_like 'a data store' end
true
7ceaf59f601e8138538e5b527ca01d245656f7aa
Ruby
waneal/discord-ttsbot
/discord-voicebot.rb
UTF-8
3,009
2.859375
3
[]
no_license
require 'discordrb' require 'aws-sdk' TOKEN = ENV['DISCORD_BOT_TOKEN'] VOICE_ID = ENV['POLLY_VOICE_ID'] TTS_CHANNELS = ENV['TTS_CHANNELS'].split(',') SampleRate = "16000" MP3_DIR = "/data/tts/mp3" NAME_DIR = "/data/tts/name" bot = Discordrb::Commands::CommandBot.new token: TOKEN, prefix: '!' bot.command(:connect, description:'読み上げbotを接続中の音声チャンネルに参加させます',usage:'!connect') do |event| channel = event.user.voice_channel unless channel event << "```" event << "ボイスチャンネルに接続されていません" event << "```" next end # ボイスチャンネルにbotを接続 bot.voice_connect(channel) event << "```" event << "ボイスチャンネル「 #{channel.name}」に接続しました。利用後は「!destroy」でボットを切断してください" event << "```" end bot.command(:destroy, description:'音声チャンネルに参加している読み上げbotを切断します', usage:'!destroy') do |event| channel = event.user.voice_channel server = event.server.resolve_id unless channel event << "```" event << "ボイスチャンネルに接続されていません" event << "```" next end bot.voice_destroy(server) event << "```" event << "ボイスチャンネル「 #{channel.name}」から切断されました" event << "```" end bot.message(in: TTS_CHANNELS) do |event| channel = event.channel server = event.server voice_bot = event.voice if voice_bot != nil if /^[^!]/ =~ event.message.to_s # `chname` で指定された名前があれば設定 if File.exist?("#{NAME_DIR}/#{server.resolve_id}_#{event.user.resolve_id}") speaker_name = "#{File.read("#{NAME_DIR}/#{server.resolve_id}_#{event.user.resolve_id}")}" else speaker_name = "#{event.user.name}" end # pollyで作成した音声ファイルを再生 polly = Aws::Polly::Client.new polly.synthesize_speech({ response_target: "#{MP3_DIR}/#{server.resolve_id}_#{channel.resolve_id}_speech.mp3", output_format: "mp3", sample_rate: SampleRate, text: "<speak>#{speaker_name}いわく、>#{event.message}</speak>", text_type: "ssml", voice_id: VOICE_ID, }) voice_bot.play_file("#{MP3_DIR}/#{server.resolve_id}_#{channel.resolve_id}_speech.mp3") end end end bot.command(:chname, min_args: 1, max_args: 1, description:'botに読み上げられる自分の名前を設定します', usage:'!chname ギャザラ') do |event, name| File.open("#{NAME_DIR}/#{event.server.resolve_id}_#{event.user.resolve_id}", "w") do |f| f.puts("#{name}") end event << "```" event << "呼び方を#{name}に変更しました。" event << "```" end bot.run
true
2fea996adc37f02dce2fa21556814963a2d6ddbe
Ruby
Nuricz/TTPS-Ruby
/práctica-4/sinatra/ej6/app.rb
UTF-8
1,707
3.421875
3
[]
no_license
require 'sinatra' class NumberToX def initialize(app) @app = app end def call(env) status, headers, response = @app.call(env) new_response = response.map { |c| c.gsub(/\d/,'x') } [status, headers, new_response] end end use NumberToX get '/' do body "GET / lista todos los endpoints disponibles (sirve a modo de documentación) <br/> GET /mcm/:a/:b calcula y presenta el mínimo común múltiplo de los valores numéricos :a y :b <br/> GET /mcd/:a/:b calcula y presenta el máximo común divisor de los valores numéricos :a y :b <br/> GET /sum/* calcula la sumatoria de todos los valores numéricos recibidos como parámetro en el splat <br/> GET /even/* presenta la cantidad de números pares que hay entre los valores numéricos recibidos como parámetro en el splat <br/> POST /random presenta un número al azar <br/> POST /random/:lower/:upper presenta un número al azar entre :lower y :upper (dos valores numéricos)" end get '/mcm/:a/:b' do |a, b| 'El mcm entre ' + a.to_s + ' y ' + b.to_s + ' es <p> ' + a.to_i.lcm(b.to_i).to_s end get '/mcd/:a/:b' do |a, b| 'El mcd entre ' + a + ' y ' + b + ' es <p> ' + a.to_i.gcd(b.to_i).to_s end get '/sum/*' do |nums| 'La suma de: ' + nums.gsub(/[{\/\\}]/, '/' => ", ") + ' es <p> ' + nums.split('/').map(&:to_i).sum.to_s end get '/even/*' do |nums| 'La cantidad de números pares entre: ' + nums.gsub(/[{\/\\}]/, '/' => ", ") + ' es <p> ' + nums.split('/').map(&:to_i).select(&:even?).size.to_s end get '/random' do rand.to_s end get '/random/:lower/:upper' do |lower, upper| rand(lower.to_i..upper.to_i).to_s end
true
08c8f7eca6c9f6f8937842ea9a6b59c4cf29a4d8
Ruby
natyv/shakeItOff
/main.rb
UTF-8
2,736
2.609375
3
[]
no_license
require 'date' require 'json' require 'sinatra' require 'pg' require "./db_config" require './models/user' require './models/food_item' require 'fatsecret' FatSecret.init('12c2ef215e604e3f8ed6853dfe478390','7cb2062d9146486eb1a137ace3819a2a') enable :sessions helpers do def current_user User.find_by(id: session[:user_id]) end def logged_in? !!current_user end def bmr if current_user.gender == 'Male' rate = 10 * current_user.weight + 6.25 * current_user.height - 5 * current_user.age + 5 else rate = 10 * current_user.weight + 6.25 * current_user.height - 5 * current_user.age - 161 end rate end end after do ActiveRecord::Base.connection.close end # The main page, shows a login form get '/' do redirect to '/dashboard' unless !logged_in? # if logged in, show the user dashboard erb :login end # Actually logging in post '/' do user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) # logged in, create a new session session[:user_id] = user.id # redirect redirect to '/' else # stay at the login form erb :login end end # shows a signup form get '/signup' do erb :signup end # creating a new user post '/signup' do user = User.new user.email = params[:email] user.password = params[:password] user.name = params[:name] user.age = params[:age] user.weight = params[:weight] user.height = params[:height] user.gender = params[:gender] user.save redirect to '/' end # displays user data get '/dashboard' do erb :index end # log out delete '/' do session[:user_id] = nil redirect to '/' end get '/food_items' do @food_items = Food_Item.where(user_id: current_user.id) erb :food_items end post '/food_items' do food_item = Food_Item.new food_item.name = params[:name] food_item.calories = params[:calories].to_i food_item.day = params[:date] #food_item.day = Date.today food_item.user_id = current_user.id food_item.save redirect to '/food_items' end get '/edit' do erb :edit end put '/edit' do user = current_user user.name = params[:name] user.age = params[:age] user.weight = params[:weight] user.height = params[:height] user.gender = params[:gender] user.save redirect to '/dashboard' end delete '/food_items' do params[:ids].each do |id| Food_Item.destroy id end {success: true}.to_json end delete '/dashboard' do user = current_user user.delete redirect to '/' end post '/food' do results = FatSecret.search_food(params[:food_name]) @result = results["foods"]["food"] erb :food end get '/food' do erb :food end get '/food_details' do @single_result = FatSecret.food(params[:food_id])["food"] erb :food_details end
true
0527b39b3761b0b0215548bf7cff5c3dd9e0fcfd
Ruby
telegeniic/Escuela_Fime
/Ruby/PosNeg.rb
UTF-8
162
3.640625
4
[]
no_license
print("ingresa un numero: ") x = gets().to_i if (x==0) then puts("Es cero") else if (x<0) then puts("Es Negativo") else puts("Es Positivo") end end
true
097f85fb00d2035bb4bbdf3b60287878f004af78
Ruby
kstephens/cabar
/lib/ruby/cabar/main.rb
UTF-8
4,668
2.671875
3
[ "MIT" ]
permissive
require 'cabar/base' require 'cabar/configuration' require 'cabar/loader' require 'cabar/resolver' require 'cabar/plugin/manager' require 'cabar/command/manager' require 'cabar/command/runner' require 'cabar/observer' require 'cabar/logger' module Cabar # Main bin/cbr script object. class Main < Base include Cabar::Observer::Observed # Raw command line arguments from bin/cbr. attr_accessor :args # The global Cabar::Configuration object. attr_accessor :configuration # The Cabar::Command::Manager for top-level commands. attr_accessor :commands # The global Cabar::Resolver that contains the available_components. # Cabar::Selection will clone this for each Command object. attr_accessor :resolver # The Cabar::Plugin::Manager manages all plugins. attr_accessor :plugin_manager # The Cabar::Logger object. attr_accessor :_logger # Returns the global Main instance. def self.current Thread.current[:'Cabar::Main.current'] || raise(Error, "Cabar::Main not initialized") end def as_current save_current = Thread.current[:'Cabar::Main.current'] Thread.current[:'Cabar::Main.current'] = self yield self ensure Thread.current[:'Cabar::Main.current'] = save_current end def initialize *args, &blk @_logger = Logger.factory. new(:name => 'cabar') super if block_given? as_current do instance_eval &blk end end end ########################################################### # Configuration # # Returns the cached Cabar::Configuration object. def configuration @configuration ||= Cabar::Configuration.new end ########################################################### # Loader # # Returns the component loader. def loader @loader ||= begin @loader = Cabar::Loader.factory. new(:main => self, :configuration => configuration) # Prime the component search path queue. @loader.add_component_search_path!(configuration.component_search_path) @loader end end ########################################################### # Plugin # # Returns the cached Cabar::Plugin::Manager object. def plugin_manager @plugin_manager ||= begin @@plugin_manager ||= Plugin::Manager.factory.new(:main => self) x = @@plugin_manager # .dup x.main = self x end end ################################################################## # Command # def commands @commands ||= begin @@commands ||= Command::Manager.factory. new() x = @@commands # .dup x end end # The cached Cabar::Command::Runner that handles parsing arguments # and running the selected command. def command_runner @command_runner ||= begin # Force loading of plugins. resolver.available_components @command_runner = new_command_runner @command_runner end end def new_command_runner Command::Runner.factory.new(:main => self, :manager => commands) end # Interface for bin/cbr. def parse_args args = self.args command_runner.parse_args(args) end # Executes the command parsed by #parse_args. # Returns the exit_code of the command. def run notify_observers :before_run @exit_code = command_runner.run ensure notify_observers :after_run end # Returns the exit_code of the last command executed. def exit_code @exit_code end ################################################################## # Main Resolver # # Return the Cabar::Resolver object. def resolver @resolver ||= begin @resolver = new_resolver # Force loading of cabar itself early. @resolver.load_component!(Cabar.cabar_base_directory, :priority => :before, :force => true) @resolver end end # Returns a new Resolver. def new_resolver opts = { } opts[:main] ||= self opts[:configuration] ||= configuration opts[:directory] ||= File.expand_path('.') Resolver.factory.new(opts) end ################################################################## def inspect to_s end end # class end # module
true
4a95f9653c90938e3570d755a560b22ce610ed69
Ruby
ErickG123/miniProjetosRubyOO
/classe_objeto.rb
UTF-8
113
2.59375
3
[]
no_license
# Definindo uma classe class MinhaClasse end # Instância de objeto objeto = MinhaClasse.new p objeto.object_id
true
2d18f93e356cb1e983e3c8167f52433ca47314ac
Ruby
zunda/sleepy-test
/web.rb
UTF-8
644
2.828125
3
[]
no_license
# vim: ts=3 sw=3: require 'sinatra' usage='/?spinup=<WAIT_SEC>;interval=<INTERVAL_SEC>;repeat=<REPEAT_NUMBER>' get '/' do content_type 'text/plain' par = Hash.new %i(spinup interval repeat).each do |k| par[k] = (params[k] || 0).to_i end stream do |out| $stdout.puts "Sleeping for #{par[:spinup]} sec for spinup" $stdout.flush sleep par[:spinup] out << "Good morning, world!, after #{par[:spinup]} seconds of sleep\n" par[:repeat].times do |i| msg = "Slept for #{par[:interval]} sec (#{i+1}/#{par[:repeat]})\n" sleep par[:interval] $stdout.puts msg $stdout.flush out << msg end out << usage + "\n" end end
true
1b11391fdab4559720d689c4153b78491e991f10
Ruby
cbbakshi/CS.169.1x
/HW1/ex1.rb
UTF-8
235
3.328125
3
[]
no_license
def palindrome?(string) string.downcase.gsub(/[^A-Za-z]/,'') == string.downcase.reverse.gsub(/[^A-Za-z]/,'') end def count_words(string) result = Hash.new(0) string.downcase.scan(/\w+/).each{|word| result[word]+=1} result end
true
52d9096059bfc8c9133224bb8adc2f848d5cbc6d
Ruby
nickmarrone/euler
/problems/003-largest-prime-factor.rb
UTF-8
92
2.8125
3
[]
no_license
require '../lib/fixnum' number = 600851475143 factors = number.factors puts factors.last
true
dd21607f90d63d23b0da301609cfb0a11889f2be
Ruby
coolsun/heist
/lib/heist/runtime/callable/macro/tree.rb
UTF-8
6,018
3.359375
3
[ "MIT" ]
permissive
module Heist class Runtime class Macro # <tt>Tree</tt>s are used by instances of +Matches+ to store expressions # matched by macro patterns. Patterns may contain patterns that repeat # (indicated by following the pattern with an ellipsis), and these # repetitions may be nested. +Tree+ instances store expressions in a set # of nested arrays that match the repetition structure of the macro # pattern being matched. See +Matches+ for a fuller explanation. # # Every +Tree+ contains an array called <tt>@data</tt> that stores the # expressions matched by a pattern variable, a variable <tt>@depth</tt> # that stores the maximum repetition depth of the tree (a non-repeated # pattern has depth zero), and an array <tt>@indexes</tt> which is used to # maintain a list of array indexes that point to the current read position # in the tree while a macro is being expanded. For example, taking the # pattern from the +Matches+ example: # # (do ([variable init step ...] ...) # (test expression ...) # command ...) # # Say we had the following expression (not entirely valid (do) syntax, but # compatible with the above pattern): # # (do ([x 6 (- x 1) (- acc 1)] # [y 5] # [acc 1 (* x acc)]) # ((zero? x) acc) # (display x) (newline) # (set! acc (* acc x))) # # The resulting +Matches+ object would contain the following data for the # variable +step+: # # "step" => [ [ (- x 1), # (- acc 1) # ], # # [], # # [ (* x acc) # ] # ] # # That is, the outermost repetition <tt>[variable init step ...]</tt> # occurs three times; the first appearance includes two matches for # <tt>step ...</tt>, the second no matches and the third one match. With # this data, an <tt>@indexes</tt> state of <tt>[0,0]</tt> would read # <tt>(- x 1)</tt>, a state of <tt>[0,1]</tt> would read # <tt>(- acc 1)</tt>, and <tt>[2,0]</tt> would read <tt>(* x acc)</tt>; # the latter instructing the +Tree+ to get the third element of the root # array, then the first element of _that_ array to find the right value. # # In practise, all +Tree+ objects have an extra array around the data as # presented above, to make the no-repetition case consistent with the # representation for arbitrarily nested repetitions. That is, the methods # in this class expect to read from an array in general, so the # representation of a non-repeating pattern is just a single-element array # to simplify the implementation of these methods in the general case. The # first item in the <tt>@indexes</tt> array is always zero. We could # remove this extra container and add a type check on <tt>@data</tt> when # reading, but the current implementation seems more elegant for the # moment. # class Tree # A +Tree+ is initialized using the name of the pattern variable it is # associated with (for debugging purposes). def initialize(name) @name = name @data = [] @depth = 0 end # Tells the receiving +Tree+ that its pattern variable has been visited # at a repetition depth of +depth+ during pattern matching. This # allocates a new empty array at an appropriate place in the tree to # store matches (or groups of matches) if any are encountered. Calls to # this method are also used to determine the tree's maximum depth. def descend!(depth) tail(depth-1) << [] @depth = depth if depth > @depth end # Pushes an expression onto the end of the final branch of the tree. All # expressions should exist at the same depth (the tree's maximum depth), # seeing as the pattern should be followed by the same number of # ellipses every time it is encountered. def <<(value) tail(@depth) << value end # Returns the expression at the current read position as instructed by # the <tt>@indexes</tt> list. def read current(@depth)[indexes[@depth]] end # Shifts the read position at the given +depth+ along by one, by adding # 1 to one of the values in <tt>@indexes</tt>. The macro expander calls # this while walking a template to iterate over repetition branches. def shift!(depth) return if depth > @depth indexes[depth] += 1 indexes[depth] = 0 if indexes[depth] >= current(depth).size end # Returns the number of matches (or groups of matches) on the current # read branch at the given +depth+. Returns zero if no branch exists at # the given indexes. def size(depth) return nil if depth > @depth current(depth).size rescue 0 end private # Returns the rightmost branch of the tree at the given +depth+. Used # when allocating new branches as repetition blocks are entered. def tail(depth) (0...depth).inject(@data) { |list, d| list.last } end # Returns the current read branch at the given +depth+, as instructed by # the <tt>@indexes</tt> list. def current(depth) indexes[0...depth].inject(@data) { |list, i| list[i] } end # Initializes the <tt>@indexes</tt> list once the maximum depth is # known, and returns the list thereafter. def indexes @indexes ||= (0..@depth).map { 0 } @indexes end end end end end
true
e36f75c7079c56fe84dc03193d7a423cc65cd383
Ruby
kevindjacobson/minecraft_api
/lib/minecraft_api.rb
UTF-8
699
2.890625
3
[]
no_license
require 'socket' require 'io/wait' require_relative 'world' require_relative 'camera' require_relative 'player' class MinecraftApi attr_reader :world attr_reader :camera attr_reader :player def initialize(host = 'localhost', port = 4711) @socket = TCPSocket.new host, port @world = World.new(self) @camera = Camera.new(self) @player = Player.new(self) end def drain() if @socket.ready? $stderr.puts "Draining extra data found in socket => [#{@socket.gets.chomp}]" end end def send(data) drain() @socket.puts "#{data}" end def send_and_receive(data) send(data) @socket.gets.chomp end def close @socket.close end end
true
d3a348d89bbc7278abffe5546c44317c9b0e3139
Ruby
vertige/Scrabble
/lib/game.rb
UTF-8
4,158
3.953125
4
[]
no_license
require_relative 'dictionary' require_relative 'tile_bag' require_relative 'player' require_relative 'scoring' require_relative 'board' module Scrabble class Game attr_reader :board, :tile_bag, :dictionary, :players def initialize @board = Scrabble::Board.new @tile_bag = Scrabble::TileBag.new @dictionary = Scrabble::Dictionary.new @players = Array.new #array of players end def start puts "Welcome to Scrabble!" print "How many players will be playing? " num_players = gets.chomp while num_players.to_i < 2 #if we could mock, we would test edge cases and novelties puts "Please enter a number of players (2+)" num_players = gets.chomp end num_players.to_i.times do |i| #if we could mock, we would test results of @players print "What is Player ##{i+1}'s name? " name = gets.chomp @players << Scrabble::Player.new(name) end @players.each do |player| #first tiles drawn during setup, could mock, would check they have tiles player.draw_tiles(@tile_bag) end # draw board @board.draw #executive decision: @players[0] begins play end def play # while not game over, loop through players, show them tiles, ask for word and where to play, play word while !game_over? @players.each do |player| player.draw_tiles(@tile_bag) show_tiles(player) takes_turn(player) end end end def show_tiles(player) tiles = player.tiles.join(" ") puts "#{player.name}, these are your tiles!: #{tiles}" end def takes_turn(player) # get a word or pass puts "Play a word? y/n" answer = y_or_n if answer == 'n' puts "Passing your turn to next player" return else puts "What word do you want to play?" word = gets.chomp # check if a valid word while [email protected]_word?(word) puts "Not a valid word. Do you want to play another word?" answer = y_or_n if answer == y puts "What word do you want to play?" word = gets.chomp else puts "Passing your turn to next player" return end end player.play(word) end end def y_or_n answer = gets.chomp.downcase while answer != "y" && answer != "n" puts "Y or N" answer = gets.chomp.downcase end return answer end def location puts "Which row do you want to play your first tile? (1 for top row, #{Scrabble::BOARD_SIZE} for bottom row):" row = gets.chomp.to_i while row < 1 puts "Choose a row from 1 to #{Scrabble::BOARD_SIZE}:" row = gets.chomp.to_i end puts "Which column do you want to play your first tile? (1 for left-most column, #{Scrabble::BOARD_SIZE} for right-most row):" col = gets.chomp.to_i while col < 1 puts "Choose a column from 1 to #{Scrabble::BOARD_SIZE}:" col = gets.chomp.to_i end #TODO : Check if there's a letter to play off of in an ideal Scrabblicious world puts "Would you like to play across or down? (A or D)?:" dir = gets.chomp.upcase while dir != "A" && dir != "D" puts "Please pick a valid direction (A or D): " dir = gets.chomp.upcase end # subtract 1 from user row/col to get idx if dir == "A" check_space(word,col - 1) else check_space(word,row - 1) end # TODO Check whatever letters exist there- Scrabblicious land again end def check_space(word,index) if word.length + index > Scrabble::BOARD_SIZE #pick another spot... end end private def game_over? @players.each do |player| if player.total_score > 100 return true end end return false # TODO if both players pass end end #end of Game class #Game Play # # new_game = Game.new # new_game.start # new_game.play end # end of module
true
96db0ad8ac9c23232e7e52d35a36239c3005169c
Ruby
afonsir/experiments
/ruby/optimization/fibo.rb
UTF-8
458
3.3125
3
[]
no_license
require 'benchmark' def fib(nth) return if nth.negative? seq = [0, 1] (1...nth).each { |i| seq << seq[i - 1] + seq[i] } seq[nth] end def r_fib(nth) return 1 if [0, 1].include? nth r_fib(nth - 1) + r_fib(nth - 2) end memory_before = `ps -o rss= -p #{Process.pid}`.to_i / 1024 time = Benchmark.realtime do puts r_fib(35) end memory_after = `ps -o rss= -p #{Process.pid}`.to_i / 1024 puts memory_after - memory_before puts time.round(2)
true
866bbe518a7f643594f127ae3346a3e36642cb6b
Ruby
kinsbrunner/interview-cake-ruby
/13-find-rotation-point/lib/Dictionary.rb
UTF-8
966
3.875
4
[]
no_license
class Dictionary attr_reader :words def initialize(words = []) @words = words end def find_rotation_point first_word = words[0] floor_index = 0 ceiling_index = words.length - 1 # Improvement to be able to process fully-ordered arrays return 0 if first_word < words[-1] while floor_index < ceiling_index # guess a point halfway between floor and ceiling guess_index = floor_index + ((ceiling_index - floor_index) / 2) # if guess comes after first word if words[guess_index] > first_word # go right floor_index = guess_index else # go left ceiling_index = guess_index end # if floor and ceiling have converged if floor_index + 1 == ceiling_index # between floor and ceiling is where we flipped to the beginning # so ceiling is alphabetically first return ceiling_index end end end end
true
709b5c50833b70d1bfa15c5d711dedc5794a3a40
Ruby
MartinCrane/reverse-each-word-web-0217
/reverse_each_word.rb
UTF-8
230
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(string) arr = string.split(" ") # sentence = "" # arr.each do |word| # sentence = sentence + word.reverse + " " # end # sentence = sentence[0..-2] (arr.collect {|x| x.reverse}).join(" ") end
true
f3b3e2f19af08a38a4f564499034e5ce04255f37
Ruby
dafurios/taller-rack
/desafio-rack2/config.ru
UTF-8
1,716
3.03125
3
[]
no_license
# Ejercicio 02 require 'rack' class MiSegundaWebApp # def call(env) # if env['REQUEST_PATH'] == '/' # [202, { 'Content-Type' => 'text/html' }, ['<h1> INDEX </h1>']] # end # end # end def call(env) case env['REQUEST_PATH'] when '/' [202, { 'Content-Type' => 'text/html' }, ['<h1> INDEX </h1>']] when '/index' [200, { 'Content-Type' => 'text/html; charset= "utf-8"' }, ['<h1> Estás en el Index! </h1>']] when '/otro' [200, { 'Content-Type' => 'text/html; charset= "utf-8"' }, ['<h1> Estás en otro landing! </h1>']] else [404, {'Content-Type' => 'text/html; charset= "utf-8"'}, [File.read("404.html")]] end end end run MiSegundaWebApp.new # Crear un archivo llamado 404.html cuyo body contenga una etiqueta de título # con el texto "No se ha encontrado la página :(". # 1. Modificar el archivo config.ru para adaptarlo a los siguientes # requerimientos: # Si se ingresa a la url /index: # Agregar un código de respuesta 200. # Agregar en los Response Headers un Content-type de tipo text/html. # Agregar en el Response Body una etiqueta de título que contenga un texto # "Estás en el Index!". # 2. Si se ingresa a la url /otro: # Agregar un código de respuesta 200. # Agregar en los Response Headers un Content-type de tipo text/html. # Agregar en el Response Body una etiqueta de título que contenga un texto # "Estás en otro landing!". # 3. Si se ingresa a cualquier otra url: # Agregar un código de respuesta 404. # Agregar en los Response Headers un Content-type de tipo text/html. # Agregar en el Response Body el archivo 404.html creado al inicio.
true
ddf9be4a1cdac8142633133502a7dfe96e5a3d9a
Ruby
mkopsho/oo-student-scraper-onl01-seng-ft-050420
/lib/scraper.rb
UTF-8
1,054
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'pry' class Scraper def self.scrape_index_page(index_url) page = Nokogiri::HTML(open(index_url)) page.css(".student-card").collect do |student| { :name => student.css(".student-name").text, :location => student.css(".student-location").text, :profile_url => student.css("a").attribute("href").value } end end def self.scrape_profile_page(profile_url) page = Nokogiri::HTML(open(profile_url)) hash = {} socials = page.css(".vitals-container a").collect do |link| link.attribute("href").value end #binding.pry socials.each do |link| if link.include?("twitter") hash[:twitter] = link elsif link.include?("linkedin") hash[:linkedin] = link elsif link.include?("github") hash[:github] = link else hash[:blog] = link end end hash[:profile_quote] = page.css(".profile-quote").text hash[:bio] = page.css(".details-container p").text #binding.pry hash end end
true
870adadd39b040f32b691186dbbf5228f29d81f3
Ruby
satgo1546/project904
/check.rb
UTF-8
1,818
3.140625
3
[]
no_license
#!/usr/bin/env ruby def no(i, line) puts "#{i.to_s} #{line}" system "pause" end File.open("data.txt", "r") do |f| pattern = { :page => /^\[\d+\]$/, :chinese_sentence => /^[“”A-Za-z0-9]*[一-龠][A-Za-z0-9一-龠,。、;:‘’“”!?·《》()]+$/, :english_sentence => /^[ -~‘’“”]+ [ -~‘’“”]+$/, :english_word => /^[A-Za-z]+$/, :empty => /^$/, } permit = { :page => true, :chinese_sentence => false, :english_sentence => false, :english_word => false, :empty => false, } i = 0 f.each_line do |line| i += 1 line.chomp! case line when pattern[:page] if not permit[:page] no i, line end permit[:page] = false permit[:chinese_sentence] = false permit[:english_sentence] = false permit[:english_word] = true permit[:empty] = false when pattern[:chinese_sentence] if not permit[:chinese_sentence] no i, line end permit[:page] = false permit[:chinese_sentence] = false permit[:english_sentence] = true permit[:english_word] = false permit[:empty] = false when pattern[:english_sentence] if not permit[:english_sentence] no i, line end permit[:page] = false permit[:chinese_sentence] = false permit[:english_sentence] = true permit[:english_word] = false permit[:empty] = true when pattern[:english_word] if not permit[:english_word] no i, line end permit[:page] = false permit[:chinese_sentence] = true permit[:english_sentence] = false permit[:english_word] = false permit[:empty] = false when pattern[:empty] if not permit[:empty] no i, line end permit[:page] = true permit[:chinese_sentence] = false permit[:english_sentence] = false permit[:english_word] = true permit[:empty] = false end end end no(0, "END")
true
6b937c4aa12ff6210c21c13606ccffc6ec8db6b0
Ruby
jnastya/bases-Ruby
/lesson3/module_accessor.rb
UTF-8
820
2.90625
3
[]
no_license
module Accessors def attr_accessor_with_history(*names) attr_accessor :history names.each do |name| var_name = "@#{name}".to_sym define_method(name) { instance_variable_get(var_name) } define_method("#{name}=") do |value| instance_variable_set(var_name, value) @history ||= {} @history[name] ||= [] @history[name] << value end define_method("#{name}_history") { @history[name] } end end def strong_attr_accessor(attr_name, type) var_name = "@#{attr_name}".to_sym define_method(attr_name) { instance_variable_get(var_name) } define_method("#{attr_name}=") do |value| if value.is_a? type instance_variable_set(var_name, value) else raise ArgumentError.new("Invalid Type") end end end end
true
499fc4efaaf78ef984bde944440c92efa698d931
Ruby
project-kotinos/reinteractive___wallaby
/lib/utils/wallaby/cell_utils.rb
UTF-8
1,022
2.53125
3
[ "MIT" ]
permissive
module Wallaby # Cell utils module CellUtils class << self # Render a cell and produce output # @param context [ActionView::Context] # @param file_name [String] # @param locals [Hash] # @return [String] output def render(context, file_name, locals = {}, &block) snake_class = file_name[%r{(?<=app/).+(?=\.rb)}].split(SLASH, 2).last cell_class = snake_class.camelize.constantize Rails.logger.info " Rendered [cell] #{file_name}" cell_class.new(context, locals).render_complete(&block) end # Check if a partial is a cell or not # @param partial_path [String] # @return [true] if partial is a `rb` file # @return [false] otherwise def cell?(partial_path) partial_path.end_with? '.rb' end # @param action_name [String, Symbol] # @return [String, Symbol] action prefix def to_action_prefix(action_name) FORM_ACTIONS[action_name] || action_name end end end end
true
36ba7e59617cd84352cdb89468255ee5b3db2618
Ruby
AnaBoca/bootcamp-ruby-challenges
/linkedlist2_challenge.rb
UTF-8
1,335
4.1875
4
[]
no_license
# Reverse a linked list using mutation class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end def print_values(list) if !list puts "nil\n" return else print "#{list.value} --> " print_values(list.next_node) end end def reverse_list(list, previous = nil) if list next_node = list.next_node list.next_node = previous reverse_list(next_node, list) # puts "#{__method__}: next_node =#{next_node.inspect}, list = #{list.inspect}" end return previous end end def infinite_loop?(list) tortoise = list.next_node hare = list.next_node until hare.nil? hare = hare.next_node return false if hare.nil? hare = hare.next_node tortoise = tortoise.next_node return true if hare == tortoise end return false end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) puts "Reverse LinkedList\n\n" node3.print_values(node3) puts '---------' node3.reverse_list(node3) node1.print_values(node1) puts "\n\n" puts "Bonus - Infinite LinkedList\n\n" puts infinite_loop?(node3) node1.next_node = node3 puts infinite_loop?(node3)
true
f1b14e3ace92ecbf7d356c6fc7eb66a2be2abef7
Ruby
eduardodelcastillo/Calculator
/calculator.rb
UTF-8
1,478
4.21875
4
[]
no_license
#calculator.rb result = 0 operation = "" operator = "" num1 = 0 num2 = 0 quit_var = "" def say(msg) puts "------ #{msg} ------" end class String def numeric? Float(self) != nil rescue false end end loop do loop do say("Please enter the first number (q to quit).") num1 = gets.chomp quit_var = num1 if num1 == "q" break elsif !num1.numeric? say("Please enter a valid number.") else break end end if quit_var == 'q' then break end loop do say("Please enter the second number (q to quit).") num2 = gets.chomp quit_var = num2 if num2 == "q" break elsif !num2.numeric? say("Please enter a valid number.") else break end end if quit_var == 'q' then break end loop do say("What do you want to do?") say("1 - Add, 2 - Subtract, 3 - Multiply, 4 - Divide, q - quit") operator = gets.chomp quit_var = operator case operator when "1" result = num1.to_f + num2.to_f operation = "+" when "2" result = num1.to_f - num2.to_f operation = "-" when "3" result = num1.to_f * num2.to_f operation = "*" when "4" result = num1.to_f / num2.to_f operation = "/" when "q" break else say("Please enter 1, 2, 3 or 4 for a valid operation.") end say("#{num1} #{operation} #{num2} equals #{result}.") break end if quit_var == 'q' then break end end
true
d4993d2de762fbbe3116734c9a5212a908430bb5
Ruby
lpotepa/euler
/19.rb
UTF-8
765
4
4
[]
no_license
def solution count = 0 last_starting_day = nil (1901..2000).each do |year| (1..12).each do |month| starting_day = last_starting_day || 6 month_days = month_days(month, year) (starting_day..month_days).step(7).each do |day| last_starting_day = 7 - (month_days - day) count += 1 if last_starting_day == 1 end end end count end def month_days(month, year) if [1,3,5,7,8,10,12].include? month 31 elsif [4,6,9,11].include? month 30 elsif month == 2 if leap?(year) 29 else 28 end end end def leap?(year) if century?(year) year % 400 == 0 else year % 4 ==0 end end def year_days(year) leap?(year) ? 366 : 365 end def century?(year) year % 100 == 0 end
true
3263e1fb5ab03b808eb1a92befca73001c2efd48
Ruby
celluloid/celluloid
/lib/celluloid/proxy/sync.rb
UTF-8
800
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# A proxy which sends synchronous calls to an actor class Celluloid::Proxy::Sync < Celluloid::Proxy::AbstractCall def respond_to?(meth, include_private = false) __class__.instance_methods.include?(meth) || method_missing(:respond_to?, meth, include_private) end def method_missing(meth, *args, &block) raise ::Celluloid::DeadActorError, "attempted to call a dead actor: #{meth}" unless @mailbox.alive? if @mailbox == ::Thread.current[:celluloid_mailbox] args.unshift meth meth = :__send__ # actor = Thread.current[:celluloid_actor] # actor = actor.behavior.subject.bare_object # return actor.__send__(*args, &block) end call = ::Celluloid::Call::Sync.new(::Celluloid.mailbox, meth, args, block) @mailbox << call call.value end end
true
5bd37f2f4a8c3daf7500643eae9b55e6e0ae85aa
Ruby
MadeInMemphisEntertainment/lyrics_finder
/spec/lyrics_finder/providers/lyrics_mania_spec.rb
UTF-8
526
2.53125
3
[ "MIT" ]
permissive
# encoding: UTF-8 describe LyricsFinder::Provider::LyricsMania do describe '.format_url' do context 'with valid author and title' do let(:song) { Song.new("amêricàn authors", "best day of my life") } let(:lyrics_mania) { LyricsFinder::Provider::LyricsMania.new(song) } let(:valid_url) { "http://www.lyricsmania.com/best_day_of_my_life_lyrics_american_authors.html" } it 'returns a properly formatted url' do expect(lyrics_mania.format_url).to eq valid_url end end end end
true
f9ccf4f092cd8a8d8cd4bb18ee243d0adbf7cb4d
Ruby
FKnottenbelt/LS_100_part1
/lssg_problems/session_6apr2018/easy.rb
UTF-8
802
4.3125
4
[]
no_license
# 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. Strings passed in will # consist of only letters and spaces. Spaces will be included only # when more than one word is present. # i: sentence # o: string with words of more than 5 letters reversed # f: split into words # loop trough words # - if size of word is >= 5 then reverse word # and add to output # - otherwise just add to output def spinWords(sentence) sentence.split().map do |word| word.size >= 5 ? word.reverse! : word end.join(' ') end p spinWords("Hey fellow warriors") == "Hey wollef sroirraw" p spinWords("This is a test") == "This is a test" p spinWords("This is another test") == "This is rehtona test"
true
3e59fd1b24cfb5053c2ec98424bbeb4cc33ee6a8
Ruby
curvgrl5000/Shaw_Exercises
/ext37.rb
UTF-8
49,361
4.40625
4
[]
no_license
# EXERCISE 37: SYMBOL REVIEW ############################################################################################### # It's time to review the symbols and Ruby words you know, and to try to pick up a few more for the next few lessons. What I've done here is written out all the Ruby symbols and keywords that are important to know. # In this lesson take each keyword, and first try to write out what it does from memory. Next, search online for it and see what it really does. It may be hard because some of these are going to be impossible to search for, but keep trying. # If you get one of these wrong from memory, write up an index card with the correct definition and try to "correct" your memory. If you just didn't know about it, write it down, and save it for later. # Finally, use each of these in a small Ruby program, or as many as you can get done. The key here is to find out what the symbol does, make sure you got it right, correct it if you do not, then use it to lock it in. # KEYWORDS ######################################################################################## puts "alias :::\\:::\\" *8 # 1. alias # The 'alias' method creates an alias for an existing method, operator, or global variable. by creating a second name. Aliasing can be used either to provide more expressive options to the programmer using the class, or to help override methods and change the behavior of the class or object. Ruby provides this functionality with the 'alias' and 'alias_method' keywords. # Ex: One class Blowdryer def on puts "The blowdryer is on!" end alias :start :on end blow = Blowdryer.new blow.start # same as .on # Ex: Two class Oven def on puts "The big oven is on." end end hot = Oven.new hot.on class Oven alias :hot_on1 :on def on puts "Warning: Don't burn your hair when you're baking the cake!" hot_on1 end end hot.on # Ex: Three, Message for this specific oven class <<hot alias :hot_on2 :on def on puts "This oven is weak, add extra time and don't burn your hair!" hot_on2 end end hot.on # Displays extra message hot2 = Oven.new hot2.on # Does not display extra message puts #blank ######################################################################################## puts "and :::\\:::\\" *8 # 2. and # Logical operator; same as && except and has lower precedence. The binary "and" operator will return the logical conjunction of both the operands. # And what does 'logical conjunction' mean, I hear you ask? http://en.wikipedia.org/wiki/Logical_conjunction a = 10 b = 20 (a and b) # is true (a && b) # is true puts # blank ######################################################################################## puts "BEGIN :::\\:::\\" *8 # 3. BEGIN # Code, enclosed in { code }, is decared to be called before the program is run. puts "Hey! Check out how this sentence is printing after the string in the BEGIN statement." BEGIN { puts "And this string will print first, when the program runs" } puts # blank ######################################################################################## puts "begin :::\\:::\\" *8 # 4. begin # 'begin' expression executes a code block or group of statements; returns the value of the last evaluated expression and then closes with 'end' expression. What's interesting to me is why 'begin' and 'end' are used, # and this lies in the what kind of ruby syntax they are: conditional expressions of control structures. # Ex: 1 temp = 97.5 begin print "It's going to be " + temp.to_s + " Fahrenheit today. " puts "And it's getting hotter every day." temp += 0.3 # this controls how the numbers get calculated forward. end while temp < 98.2 puts #blank line # Ex: 2 begin puts 'I am before the raise statement in this code block.' raise 'Shoot, an error has occurred, I am the raise statement.' puts 'I am after the raise statement.' rescue puts 'Whoa, I am rescued.' end puts 'I am after the begin block.' puts #blank line # Ex: 3 a = 1 b = 2 c = 3 begin raise "Testing #{a}, #{b}, #{c}" rescue Exception => e puts e.message puts e.backtrace.inspect # prints the 'Exception'... # 'backtrace' method returns an array of strings, # each containing the 'filename:line No in the method # 'inspect' method returns the exception’s class name end puts #blank line # What's between that begin and end? # begin...end (what is called block in other languages) may sometimes be referred to simply as what it is, # i.e. an expression (which may in turn contain other expressions - an expression is simply something that has a return value) in Ruby. Some references will still call it a begin/end block, or a code block, adding somewhat to the confusion # do...end or {...} will always be referred to as a block in Ruby ######################################################################################## puts "break :::\\:::\\" *8 # 5. break # Terminates a 'while' or 'until' loop or a method inside a block. Exits from the most internal loop. # 'break' is also a conditional expression of ruby's control structures. # Ex: 1 i=0 while i<3 print i, "\n" # '\n' returns a newline. This symbol is part of ruby's backslash notation. break end # Ex: 2 six = (1..10).each {|i| break i if i > 5} puts six # 6 puts # blank ######################################################################################## puts "case :::\\:::\\" *8 # 6. case # Compares the expression specified by case and that specified by when using the === operator and # executes the code of the 'when' clause that matches. # The expression specified by the 'when' clause is evaluated as the left operand. # If no when clauses match, case executes the code of the else clause. # 'case' is thus a conditional expression that is a ruby conditional structure. # A 'when' statement's expression is separated from code by the reserved word then, a newline, or a semicolon. # Ex: 1 $age = 5 case $age when 0 .. 2 # Here we use a rane puts "baby girl" when 3 .. 6 puts "little girl" when 7 .. 12 puts "girl" when 13 .. 18 puts "young woman" else puts "female adult" end puts # blank line # Ex: 2 collection = "Wrap-Around Dress" designer = case collection when "Chiffon Evening Gown" then "ALBERTA FERRETTI" when "Poplin Dress" then "CHLOE" when "Wrap-Around Dress" then "DVF" when "Essential Line" then "DKNY" when "Baguette Handbag" then "FENDI" when "Berkin Handbag" then "HERMES" when "Pink Silk Pantsuit" then "J.CREW" when "Conical Bra" then "JEAN PAUL GAULTIER" when "Black Nylon Bag" then "KATE SPADE" when "Jap-Wrap" then "KENZO" else "Unknown" end puts "The " + collection + " is signature to " + designer puts # blank ######################################################################################## puts "class :::\\:::\\" *8 # 7. class # Mirroring the real world, object oriented languages like Ruby, take objects and classify them. # So when a category is created like "shoes", it's called a 'class', and an object that belongs to the class "shoes" # is called an instance of that class. So to create an object of that class, you have to define its characteristics. # And finally a new method defined in that class is also a new instance of tha class. # A class definition is a region of code between the keywords 'class' and 'end'. # Making a new instance of a class is sometimes called instantiating or initializing that class, like # you'll see below in the class I've made and the object I've created. # Ex: 1 class Shoes def initialize( type, color, season ) @type = type @color = color @season = season end def kind_of_shoe puts "My favorite type of shoes are #{@type}." end def shade puts "And they always seem to be #{@color}." end def seasonable puts "And everybody knows the best season for #{@type} is #{@season}." end end new_shoes = Shoes.new( "wedges", "black", "fall") new_shoes.kind_of_shoe new_shoes.shade new_shoes.seasonable puts # blank # Ex: 2 class Yo_girlfriend def initialize( name ) @name = name end def hello_there puts "Yo, " + @name + "!" end end hi = Yo_girlfriend.new( "Girlfriend" ) hi.hello_there puts # # Ex: 3 class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def to_s puts "Song: #{@name}--#{@artist} (#{@duration} min)" end end aSong = Song.new("Respect", "Aretha Franklin", 2.60) aSong.to_s puts # blank # Ex: 4 class Student @@no_of_students=0 # class variables def initialize(id, name, addr) @stud_id=id @stud_name=name @stud_addr=addr end def display_details() puts "Student id #@stud_id" puts "Student name #@stud_name" puts "Student address #@stud_addr" end def total_no_of_students() @@no_of_students += 1 puts "Total number of students: #@@no_of_students" end end # Create Objects cust1=Student.new("1", "Sarah", "2250 S. Street, Washinton, D.C.") cust2=Student.new("2", "Lana", "1220 N. Post Rad, Boston, Mass") # Call Methods cust1.display_details() cust1.total_no_of_students() cust2.display_details() cust2.total_no_of_students() puts # blank ######################################################################################## puts "def :::\\:::\\" *8 # 8. def # Defines a method; closes with end. def purchase(arg1) @thing = arg1 puts "The price for the #{@thing} has been approved." end puts purchase("iPad") ######################################################################################## puts "defined? :::\\:::\\" *5 # 9. defined? # Determines if a variable, method, super method, or block exists. It's a special operator # that takes the form of a method and determines whether or not the passed expression is # defined. THen it returns a description string of the expression, or 'nil' if the expression # isn't defined. # Ex: 1 - Run this in IRB grl_action_figure = 42 defined? grl_action_figure # => "local-variable" defined? $_ # => "global-variable" defined? men # => nil (undefined) # Ex: 2 defined? puts # => "method" defined? puts(bar) # => nil (bar is not defined here) defined? unpack # => nil (not defined here) # Ex: 3 defined? super # => "super" (if it can be called) defined? super # => nil (if it cannot be) # Ex: 4 defined? yield # => "yield" (if there is a block passed) defined? yield # => nil (if there is no block) puts #blank line ######################################################################################## puts "do :::\\:::\\" *5 # 10. do # Begins a block and executes code in that block; closes with end. # For instance a 'while' loop's conditional is seperated from code by the reserved word 'do', # a newline, backslash '\', or a semi-colon ';'. # Ex: 1 $x = 0 $num = 5 while $x < $num do puts("The loop will keep groovin' until x = #$x" ) $x +=1 end puts # blank # Ex: 2 (0..5).each do |y| puts "Value of the local variable in the range is #{y}." end puts # blank # Ex: 3 $z = 0 $num = 5 until $z > $num do puts("Until z is greater than the number, it will keep looping. So far z = #$z." ) $z +=1; end puts # blank ######################################################################################## puts "if :::\\:::\\" *5 # 11. if # Executes code block if true. Closes with end. puts "elsif ::\\:::\\" *5 # 12. elsif # Executes if previous conditional, in if or elsif, is not true. puts "else :::\\:::\\" *5 # 13. else # Executes if previous conditional, in if, elsif, unless, or when, is not true. # Ex: 1 def prompt() print "> " end def give(gived) puts "#{gived} You'll get reincarnated into swan. Keep it up, don't go backwards." # Process.exit(0) end def try(try_again) puts "#{try_again} You'll get reincarnated into large earth worm. Try again tomorrow, please!" end def start() puts "There's homeless women outside the restaurant you just exited." puts "You've got left-overs of your favorite dish." puts "Do you give her your leftovers? Yes? or No?" prompt; next_move = gets.chomp if next_move.include? "yes" give("Good karma wins!") elsif next_move.include? "no" try("Bad karma, mon.") else puts "Not sure about this question? Meditate and try again." start() end end start() ######################################################################################## puts "END :::\\:::\\" *5 # 14. END # Code, enclosed in { code }, will be declared to be called at the end of the program. END { puts "Cheerio, see you next time!"} # This will run at the end of the program. puts #blank ######################################################################################## puts "end :::\\:::\\" *5 # 15. end # 'end', literal ends the code block (group of statements) starting with begin, def, do, if, etc. # Ex: 1: class Nails def initialize(digits, comment) @digits = digits @comment = comment end # So here we're ending the initialization def press puts "Take care of your #{@digits} little piggies at Nite Spa, Venice. They're open late, #{@comment}." end # So here we are ending the method end # So here we are ending the class handy = Nails.new(10, "which makes me weak in the knees") handy.press puts # blank ######################################################################################## puts "ensure :::\\:::\\" *5 # 16. ensure # Always executes at block termination; use after last rescue. # An ensure clause runs whether an exception is raised or not # An ensure clause without an explicit return statement does not alter the return value. # Ex: 1 require 'open-uri' require 'timeout' remote_base_url = "http://en.wikipedia.org/wiki" start_year = 1997 end_year = 2000 (start_year..end_year).each do |yr| begin rpage = open("#{remote_base_url}/#{yr}") rescue StandardError=>e puts "Error: #{e}" else rdata = rpage.read ensure puts "I'm busy at work gathering from wikipedia!" sleep 5 end if rdata File.open("copy-of-#{yr}.html", "w"){|f| f.write(rdata) } end end puts # blank ######################################################################################## puts "false :::\\:::\\" *5 # 17. false # Logical or Boolean false, instance of FalseClass. (See true.) # false: Value representing false. It's a Pseudo-variable and its a reserved word. print defined?(t2), "\n" # false puts # blank ######################################################################################## puts "for :::\\:::\\" *5 # 18. for # Begins a 'for' loop; used with in. A special Ruby keyword that indicates the beginning of the loop. It's an example of how you can get more done with tedius tasks. # Ex: 1 for current_iteration_number in 1..10 do # here we're using a range that defines the variable and then 'do' activates the value gathering puts "Hello world, this is number #{current_iteration_number}" # This prints until the end of the range is reached, which in this case is 10. end puts # blank # Ex: 2 for i in 1..100 puts i if i % 7==0 end puts # blank ######################################################################################## puts "in :::\\:::\\" *5 # 19. in # in is an extension to object. class Object # Returns true if the object sent #in is included in the argument list. # # Using in like this avoids accidental assignment, like .eql?, but unlike .eql? # has the same semantics as ==, which is often idea. # def in(*ary) ary.include?(self) end color = [] # Usage in conditionals: # if 1.in 1, 2, 3 puts "1 was included" end if "x".in "xyz" puts "x was included" end if color.in :white, :gray, :black puts "#{color} isn\'t a color." end # It can also be used a safe alternative to ==. # if 1.in 1.0 puts "1 == 1.0 #=> true" end # end puts # blank ######################################################################################## puts "module :::\\:::\\" *5 # 20. module # Defines a module; closes with end. A 'module' is a collection of methods classes and constants. # The methods in a module maybe instance methods or module methods. # Instance methods appear as methods in a class when the module is included, module methods do not. # Modules provide a namespace and prevent name clashes and theyi mplement the 'mixin' facility # By defining a 'namespace' they create a special space wheteby they can exist without having to # clash with other methods and constants. module Week FIRST_DAY = "Sunday" def self.weeks_in_month puts "You have four weeks in a month" end def self.weeks_in_year puts "You have 52 weeks in a year" end end class Decade include Week @@no_of_yrs=10 def no_of_months puts Week::FIRST_DAY number=@@no_of_yrs * 12 puts number end end d1=Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months puts # blank ######################################################################################## puts "next :::\\:::\\" *5 # 21. next # Jumps before a loop's conditional. Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil). # Ex: 1 for i in 0..10 if i < 5 then next end puts "Value of local variable is #{i}" end puts # blank ######################################################################################## puts "nil :::\\:::\\" *5 # 22. nil # Jumps before a loop's conditional. # Empty, uninitialized variable, or invalid, but not the same as zero; object of NilClass. # nil: Value representing undefined. It's a Pseudo-variable and its a reserved word. # the sole instance of the Class NilClass(represents false) # In Ruby every value is an object. So, nil is an object, too. In fact, it is an instance of the NilClass: my_object = "worth a fortune." if my_object.nil? puts "There is no object!" else puts "The value of the object is #{my_object}" end nil.class nil == nil # Which will render true 5.nil? # false {:a => 1}[:b].nil? # true nil.nil? # true nil.object_id # 4 # Why is the object id of nil equal to 4? First, you need to know that false and true variables work exactly the same way as nil does. They are singleton instances of FalseClass and TrueClass, respectively. When the Ruby interpreter boots up, it initializes FalseClass, TrueClass and NilClass. The result is: false.object_id # 0 true.object_id # 2 nil.object_id # 4 # What happened to 1 and 3? Well, the first bit is reserved for Fixnum values (numbers) only. # Simple and consistent. puts # blank ######################################################################################## puts "not :::\\:::\\" *5 # 23. not # Logical operator; same as !. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. # Ex: 1 not(a && b) #false # Ex: 2 x, me = "me" you = "you" x = me not me x = you puts x puts # blank ######################################################################################## puts "or :::\\:::\\" *5 # 24. or # Logical operator; same as || except or has lower precedence. # Ex: 1 def prompt() puts "Type in anything.... " end def get_foo(thing) @thing = thing "foo is found here: #{@thing}" end prompt; get_foo = gets.chomp foo = get_foo("") or raise "Could not find foo!" # Comment out all instances of foo and OR will take over by # initiating the 'raise' method. # Ex: 2 ruby = "dynamic" programming = "ruby" if ruby == "dynamic" or programming == "mind-bending" puts "|| or" end ruby = "awesome" if ruby == "dynamic" or programming == "mind-bending" puts "|| or" else puts "sorry!" end if !(ruby == "dynamic" or programming == "mind-bending") puts "nope!" end puts # blank ######################################################################################## puts "redo :::\\:::\\" *5 # 25. redo # Jumps after a loop's conditional. Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block. # Ex: 1 limit = 851 (223..1000000).each do |num| if num.to_i % 2 == 0 num = 1.541645637 * num puts num break if num > limit redo end end puts # blank ######################################################################################## puts "rescue :::\\:::\\" *5 # 26. rescue # Evaluates an expression after an exception is raised; used before ensure. # Ex: 1 a = 10 b = "42" begin a + b rescue puts "Could not add variables a (#{a.class}) and b (#{b.class})" else puts "a + b is #{a + b}" end puts # blank ######################################################################################## puts "retry :::\\:::\\" *5 # 27. retry # Repeats a method call outside of rescue; jumps to top of block (begin) if inside rescue. # If retry appears in rescue clause of begin expression, restart from the beginning of the begin body. # Ex: 1 A typical pattern would start like this: # begin # do_something # exception raised # rescue # # handles error # retry # restart from beginning # end # Ex: 2 # Here, you can get a better idea of what both Ensure and Retry are doing: attempts = 0 begin make_service_call() rescue Exception attempts += 1 retry unless attempts > 2 # exit -1 ensure puts "ensure! #{attempts}" end # Try this gem out, it's suppose to be take care of the retry situations nicely, # thier example is as follows: http://retry.rubyforge.org/ # THIS IS not eveluationg correctly. Ask womone tomorrow! puts # blank ######################################################################################## puts "return :::\\:::\\" *5 # 28. return # Returns a value from a method or block. May be omitted. The return statement in ruby is used to return one value from a Ruby Method. # Ex: 1 def sampling_1 return 'Apples', 4+2, [5,4,3,2] end puts sampling_1.inspect # ["Apples", 6, [5, 4, 3, 2]] # Ex: 2 def sampling_2 l = 100 m = 200 n = 300 return l, m, n end var = sampling_2 puts var.inspect # Ex: 3 def sampling3 return 1,2,3 end puts sampling3 puts # blank ######################################################################################## puts "self :::\\:::\\" *5 # 29. self # Current object (invoked by a method). The keyword self in Ruby gives you access to the current object – the object that is receiving the current message. # Ex: 1 class Post class << self def print_author puts "The author of all posts is Anna" end end end Post.print_author puts # blank ######################################################################################## puts "super :::\\:::\\" *5 # 30. super # Calls method of the same name in the superclass. The superclass is the parent of this class. class Song def to_s "Song: #{@name}--#{@artist} (#{@duration})" end end class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end def to_s super + " [#{@lyrics}]" end end aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") puts aSong.to_s # "Song: My Way--Sinatra (225) [And now, the...]" puts # blank ######################################################################################## puts "then :::\\:::\\" *8 # 31. then # A continuation for if, unless, and when. May be omitted. # In english, "ternary" is an adjective meaning "composed of three items." # In a programming language, a ternary operator is simply short-hand for an if-then-else construct. # In Ruby, '?' and : can be used to mean 'then' and 'else' respectively. def check_sign(number) number > 0 ? "#{number} is positive" : "#{number} is negative" end puts check_sign(200) def check_sign(number) number > 0 ? "#{number} is positive" : "#{number} is negative" end puts check_sign(-200) puts # blank ######################################################################################## puts "true :::\\:::\\" *5 # 32. true # Logical or Boolean true, instance of TrueClass. # true: Value representing true. a = 2 b = 2 puts a <= b puts # blank ######################################################################################## puts "undef :::\\:::\\" *5 # 33. undef # Makes a method in current class undefined. This cancels the method definition. An undef can not appear in the method body # Ex: 1 # method_name = 500 # undef method_name # The idea is to strip every method from your new class so that every call you make to it ends in #method_missing. That way you can implement a real proxy that just shuffles everything through. # Apparently other uses for this is in game design, when say you want a player object to add on a method given a certain situations and then have it taken away once the scope of that situation has been completed. # The flexibility of this makes it easier to work with code that needs to be handled differntly at run time pending the scope of an expression. puts # blank ######################################################################################## puts "unless :::\\:::\\" *5 # 34. unless # Makes a method in current class undefined. 'unless' is a conditional expressions of control structures. # Ex: 1 class Language lang = "de" unless lang == "de" dog = "dog" else dog = "Hund" end end test = Language.new puts test puts # blank line # Ex: 2 age=15 unless age>20 puts "girl is younger than 20" else puts "woman is older than 20" end puts # blank ######################################################################################## puts "until :::\\:::\\" *5 # 35. until # Executes code block while conditional statement is false. An unless statement is really like a negated if statement # Ex: 1 x = 1 until x > 99 puts x x = x * 2 end puts # blank line # Ex: 2 weight = 185 begin puts "Weight: " + weight.to_s weight -= 5 end until weight == 155 puts # blank line # Ex: 3 until($_ == "q") # $_ represents the last read line puts "Running..." print "Enter q to quit: " $_ = gets.chomp() end puts # blank ######################################################################################## puts "when :::\\:::\\" *5 # 36. when # 'when' starts a clause (one or more) under case. # Ex: 1 - One way to work with numbers with similar results a = 1 case when a < 5 then puts "#{a} is less than 5" when a == 5 then puts "#{a} equals 5" when a > 5 then puts "#{a} is greater than 5" end # Ex: 2 - One way to work with numbers with a similar results case a when 0..4 then puts "#{a} is less than 5" when 5 then puts "#{a} equals 5" when 5..10 then puts "#{a} is greater than 5" else puts "unexpected value #{a} " # Just in case "a" is bigger than 10 or negative. end # Ex: 3 Enter this one into IRB, and the result returns => "a fruit" fruit = "apple" case fruit when "vanilla" then "a spice" when "spinach" then "a vegetable" when "apple" then "a fruit" else "an unexpected value" end puts # blank ######################################################################################## puts "while :::\\:::\\" *5 # 37. while # Executes code while the conditional statement is true. The while statement in Ruby is very similar to if and to other languages' while (syntactically). The code block will be executed again and again, as long as the expression evaluates to true. # Ex: 1 puts "Do you live on the moon?" line = readline.chomp while line != "no" puts "Welcome back to planet earth, you never left." puts #blank # Ex: 2 File.open('good_news.txt', 'r') do |f1| while line = f1.gets puts line end end puts #blank # Ex: 3 age = nil puts "Enter age, or 0 to quit: " age = gets.to_i while (age > 0 ) do if age > 65 puts "Greetings Madame, you'll pay the Senior Fare." elsif age >= 14 puts "Greetins Miss, you'll pay the Adult Fare." elsif age >= 2 puts "Hello Child, your momma will pay the Child Fare." else puts "You rid for free!" end puts "Enter another age for the fare pricing, or 0 to quit: " age = gets.to_i end puts #blank ######################################################################################## puts "yield :::\\:::\\" *5 # 38. yield # Executes the block passed to the method - it's a method call. Evaluates the block given to the current method with arguments, if no argument is given, nil is used as an argument. The argument assignment to the block perameter is done just like multiple assignment. If the block is not supplied for the current method, an exception is raised. # In ruby, methods may receive a code block that as the name describes are used to perform arbitrarily # segments of code. When a method expects a block, it invokes it by calling the yield function. # Perfect to iterate a list or to provide a custom algorithm. # For instance, this Person class is initialized with a name, and the 'do_with_name' method when instantiated # will pass the name attribute, to the block received. # Ex: 1 class Person def initialize( name ) @name = name end def do_with_name yield( @name ) end end person = Person.new("Andrea") person.do_with_name {|string| puts "Hey, her name is #{string}" } puts #blank ######################################################################################## ######################################################################################## # DATA TYPES puts "true :::\\:::\\" *5 # 39. true # Logical or Boolean true, instance of TrueClass. # true: Value representing true. It's a Pseudo-variable and its a reserved word. i0 = 1 loop { i1 = 2 print defined?(i0), "\n" # true print defined?(i1), "\n" # true break } print defined?(i0), "\n" # true ######################################################################################## puts "false :::\\:::\\" *5 # 40. false # Logical or Boolean false, instance of FalseClass. (See true.) # false: Value representing false. It's a Pseudo-variable and its a reserved word. print defined?(i1), "\n" # false puts # blank ######################################################################################## puts "nil :::\\:::\\" *5 # 41. nil # Empty, uninitialized variable, or invalid, but not the same as zero; object of NilClass. # nil: Value representing undefined. It's a Pseudo-variable and its a reserved word. # the sole instance of the Class NilClass(represents false) # In Ruby every value is an object. So, nil is an object, too. In fact, it is an instance of the NilClass: my_object = nil if my_object.nil? puts "There is no object!" else puts "The value of the object is worthless." end nil.class nil == nil # Which will render true 5.nil? # false {:a => 1}[:b].nil? # true nil.nil? # true nil.object_id # 4 # Why is the object id of nil equal to 4? First, you need to know that false and true variables work exactly the same way as nil does. They are singleton instances of FalseClass and TrueClass, respectively. When the Ruby interpreter boots up, it initializes FalseClass, TrueClass and NilClass. The result is: false.object_id # 0 true.object_id # 2 nil.object_id # 4 # What happened to 1 and 3? Well, the first bit is reserved for Fixnum values (numbers) only. # Simple and consistent. puts # blank ######################################################################################## puts "constants :::\\:::\\" *5 # 42. constants # A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant, as shown in the example. More on CONSTANTS are discussed in 'variables. # Ex: 1 A_CONST = 10 # A_CONST = 20 Uncomment this and run it and you'll get a warning. puts A_CONST # Ex: 2 # CONSTANTS # Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. class Collection SHADE1 = "blue" SHADE2 = "red" def show puts "Color of the first shade is #{SHADE1}" puts "Color of the second shade is #{SHADE2}" end end # Create Objects object=Collection.new() object.show puts # blank ######################################################################################## puts "strings :::\\:::\\" *5 # 43. strings # A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals. # Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in “!” modify their receiver, while those without a “!” return a new String. However, there are exceptions, such as String#[]=. # Ex: 1 puts "1 + 1 = #{ 1 + 1 }." # Ex: 2 puts "Contents of this is a string." # Ex: 3 puts "%s now we're doing string formatting, with %s!" % ['Yay,', 'literals'] puts #blank line ######################################################################################## puts "numbers :::\\:::\\" *5 # 44. numbers # In Ruby, numbers without decimal points are called integers. # And numbers with a decimal point are called floating-point numbers or simply: 'floats' # An integral literal is simply a sequence of digits, like 123, 12345678. puts 1_000_000_000 # Underscores can be inserted into integer literals, often used as thousands seperators. puts 3 / 2 puts 6 * 2 / 2 + 3 puts 55.2 / 3.2 puts #blank # Ruby integers are objects of class Fixnum or Bignum. Both classes descend from Integer and # are therefore numeric. Fixnum and Bignum represent itegers of differing sizes. def sizes. # In Ruby, numbers are ######################################################################################## puts "variables :::\\:::\\" *5 # 45. variables # Variables are the memory locations which holds any data to be used by any program. # There are several types of variables. # GLOBAL VARIABLES # A global variable has a name beginning with $. It can be referred to from anywhere in a program. Before initialization, a global variable has the special value nil. Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option. $special_thing $special_thing = 10 puts $special_thing puts # blank # INSTANCE VARIABLES # Instance variables begin with @. Uninitialized instance variables have the value nil and produce # warnings with the -w option. name1 = "Liliana" name2 = "George" puts "Hello #{name1}, where is #{name2}?" puts # blank # CLASS VARIABLES # Class variables begin with @@ and must be initialized before they can be used in method definitions. # Referencing an uninitialized class variable produces an error. Class variables are shared among descendants # of the class or module in which the class variables are defined. class Poly @@sides = 15 def self.sides @@sides end end puts Poly.sides # => 15 # The issue with class variables is inheritance. Let’s say I want to subclass Polygon with Triangle like so: class Tri < Poly @@sides = 3 end puts Tri.sides # => 3 puts Poly.sides # => 3 # Wha happen, no comprende! Polygon’s sides was set to 10? When you set a class variable, you set it for the superclass and all of the subclasses. Rember this as INHERITANCE IS truly the big deal here! class Rect < Poly @@sides = 4 end puts Poly.sides # => 4 puts # blank # LOCAL VARIABLES # Instance variables begin with @. Uninitialized instance variables have the value nil and produce # warnings with the -w option. class Client def initialize(id, name, phone) @client_id=id @client_name=name @client_phone=phone end def display_details() puts "Client id #@client_id" puts "Client name #@client_name" puts "Client phone #@client_phone" end end # Create Objects client1=Client.new("1", "Jane", "310-555-1330") client2=Client.new("2", "Mary", "310-666-3333") # Call Methods client1.display_details() client2.display_details() puts # blank # CONSTANTS # Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. # Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning. Think of constants as frozen variables. class Constants VAR1 = 100 VAR2 = 200 def show puts "Value of first Constant is #{VAR1}" puts "Value of second Constant is #{VAR2}" end end # Create Objects object=Constants.new() object.show puts # blank # PSEUDO VARIABLES # They are special variables that have the appearance of local variables but behave like constants. You can not assign any value to these variables. # self: The receiver object of the current method. # true: Value representing true. # false: Value representing false. # nil: Value representing undefined. # __FILE__: The name of the current source file. # __LINE__: The current line number in the source file. puts #blank ######################################################################################## puts "ranges :::\\:::\\" *5 # 46. ranges # One of most fundamental things they do is express a sequence, with a starting point and # an ednding point and a way to produce successive falues. Sequences are created with te ".." # "..." range operatores. Two dots creates an inclusive range, three does form a range that # excludes a high value. # Ex: 1 # Ranges are represented as range objects, with references to two Fixnum objects, to conver a # range into a list, we use the 'to_a' method puts (1..5).to_a puts # blank # Ex: 2 # You can iterate over ranges with methods that test their contents: digits = 0..9 puts digits.include?(5) # true puts # blank puts digits.min # 'min' method identifies the starting fixnum: 0 puts # blank puts digits.max # 'max' method identifies the ending fixnum: 9 puts # blank puts digits.reject {|i| i < 5 } # 'reject' method rejects all numbers less than fixnums: 5,6,7,8,9 puts # blank digits.each do |digit| # 'each' method iterates over each element and places the returning puts(digit) # expression into 'digit', puts(digit) prints it end # Ex: 3 # Another way to use ranges is as Intervals. If a value falls within a range, we use the case # equality operator: '==='. puts (1..50) === 5 # true puts (16..20) === 15 # false puts (1..10) === 3.14159 # true puts ('a'..'j') === 'c' # true puts ('a'..'j') === 'z' # false ######################################################################################## puts "arrays :::\\:::\\" *5 # 47. arrays # Arrays are ordered, integer-indexed collections of any object. # Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, # an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on. # Ex: 1 first_set = ["Cookies N' Cream", "Chocoloate", "Vanilla", "Mint Chocolate Chip", "Chocolate Chip Cookie Dough", "Cookie Dough", "Strawberry", "Rocky Road", "Mint", "Coffee"] puts first_set[0, 3] puts #blank # Ex: 2 second_set = ["Banana Split", "Boston Cream Pie", "Cake Batter", "Chunky Monkey", "Cake Batter", "Cannoli", "Half Baked", "Smores", "Karmel Sutra", "Cherry Garcia"] second_set.collect! {|x| puts x + "!!"} puts #blank # Ex: 3 third_set = ["Dulce de Leche", "Choco Taco", "Tutti Frutti", "Cherimoya", "Passion-Fruit", "Strawberry Getalto", "Cinnamon Orange", "Pina Colada", "Tropical Fruit", "Watermelon Blast"] third_set.cycle(2) {|x| puts x} puts #blank puts third_set.first + ": the yummiest one!" puts #blank puts third_set.last + ": perfect for summer nights!" puts #blank puts third_set[5] + ": perfect for summer nights!" puts #blank puts third_set.shuffle! puts #blank ######################################################################################## puts "hashes :::\\:::\\" *5 # 48. hashes # A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted. # Ex: 1 Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200} Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200} Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200} puts # blank # Ex: 2 h = Hash.new("Hey, this is a default value for a key") # this returns nil puts h.default #= > Returns the value for a key that does not exist for the hash # Ex: 3 h["a"] = 100 h["b"] = 200 puts h["a"] #= > 100 puts h["c"].upcase! #= > the string, "Hey, this is passing..." is a defalut value for the key puts #blank # Ex: 4 h = { "a" => 100, "b" => 200 } h = Hash.new {|hash, key| hash[key] = puts "This is the key: #{key}" } puts h["c"] #= > This is the key: c # Ex: 5 h = { "a" => 100, "b" => 200 } h.each {|key, value| puts "#{key} is #{value}" }#= > a is 100, b is 200 puts #blank # Ex: 6 h = { "a" => 100, "b" => 200 } h.each_key {|key| puts key } #= > a, b puts # blank # Another method on the hash puts h.length #= > 2 puts #blank # Ex: 7 h = { "a" => 100, "b" => 200, "c" => 300 } puts h.values # => [100, 200, 300] puts # blank ######################################################################################## # STRING ESCAPES SEQUENCES / BACKSLASH NOTATION # \\ : single backslash puts #blank line # \' : single quote puts #blank line # \" : double quote puts #blank line # \a : bell or alert puts #blank line # \b : is the backspace character only inside a character class. puts #blank line # \b : Outside a character class, \b is a word/non-word boundary. puts #blank line # \cx : control x puts #blank line # \Cx : control x puts #blank line # \f : form feed puts #blank line # \e : escape puts #blank line # \M-x : meta x puts #blank line # \M-\C-x : meta control x puts #blank line # \n : a newline puts #blank line # \nnn : character in octal value nnn puts #blank line # \nnn : character with hexadecimal value nn puts #blank line # \unnnn : Unicode code point U+nnnn (Ruby 1.9 and later) puts #blank line # \r : carriage return puts #blank line # \s : whitespace, essentially a space puts #blank line # \t : a tab puts #blank line # \v : vertical tab puts #blank line # \xnn : character in hexadecimal value nn puts #blank line # \x : character x itself (\" a single quote, for example) puts #blank line # \z : Matches the end of the string unless the string ends with a ``\n'', # in which case it matches just before the ``\n''. puts #blank line ######################################################################################## # BRAND def OPERATORS # ( # () : Parentheses are also used to collect the results of pattern matching. # Ruby counts opening parentheses, and for each stores the result of the partial match # between it and the corresponding closing parenthesis. # : You can use parentheses to group terms within a regular expression. # Everything within the group is treated as a single regular expression. # $ # Matches end of line. puts "This is line #$." # [] References the element or holds the element set, which is expressed as one singular expression # The 'slice' method is an alias for two square brackets: [] puts '======' s = 'My kingdom for a string!' puts s.slice(3) # => 107 puts s[3] # => 107 puts 107.chr # => "k" puts s.slice(3,1) # => "k" puts s[3,1] # => "k" puts s[23,1] # => "!" puts s[24] # => "nil" # If compared to substr in other languages, this may come as a surprise; it returns the value of the character and not the rest of the string. We can do the same using ranges instead of specific indices: puts '======' s = 'My kingdom for a string!' puts s.slice(3..9) puts s[0..1] + s[17..22] + s[11..13] + s[15..15] + s[3..9] + s[23..-1] puts s.slice(0..-15) puts s[17..-1] # Ruby Bitwise Operators: puts '======' a = 78 # 01001110 b = 54 # 00110110 puts (a&b) # 6 puts (a|b) # 126 puts (a^b) # 120 puts (~a) # -79 puts (a<<2) # 312 puts (a>>2) # 19 # Ruby Logical Operators: puts '======' a = 10 b = 20 (a and b) # is true (a or b) # is true (a && b) # is true (a || b) # is true !(a && b) # is false not(a && b) # is false # Public Instance Methods / String Class Methods puts '======' # =~ # If an object is a Regexp ( regular expression), the operator matches strings against regular expressions s = 'how now brown cow' s =~ /cow/ s =~ /now/ s =~ /brown/ s =~ /dog/ # Arithmetic Operators: puts '======' # Arithmetic operators puts 3 + 4 # add puts 7 - 3 # subtract puts 3 * 4 # multiply puts 12 / 4 # divide puts 12**2 # raise to a power (exponent) puts 12 % 7 # modulo (remainder) puts '======' # When you do integer division in Ruby, any fractional part # in the result will be truncated. puts 24 / 2 # no problem puts 25 / 2 # uh-oh, truncation puts 25.0 / 2 # using a float as at least one operand solves it puts 25.0 / 2.0 # same when both operands are floats puts '======' # Unary operators puts +7 + -5 puts -20 + 32 puts -20 - +32 puts 20 * -8 puts '======' # Others puts 24.div(2) # division puts (25.0).div(2.0) # result is integer puts 12.modulo(5) # modulo puts 12.modulo(5.0) # modulo with float puts 12.divmod(5) # return array with quotient, modulus puts 12.0.divmod(5.0) # with float puts 12.quo(5) # return the quotient puts 12.remainder(5) # return the remainder puts '======' # Ruby Comparison Operators: # Comparision operators puts '======' # Test two numbers for equality with ==, eql?, !=, or <=> puts 12 == 24/2 puts 24.eql?(12*2) puts 12 == 14 puts 12 != 14 puts 12 <=> 12 puts 12 <=> 10 puts 12 <=> 14 puts '======' # Test if two numbers are equal, less than, or greater than each other puts 12 < 14 #less than puts 12 < 12 puts 12 <= 12 # less than or equal to puts 12.0 > 11.9 puts 12.0 >= 12 # greater than or equal to puts '======' # the <=> (spaceship operator) returns -1, 0, or 1, # depending on whether the first value is equal to the second (0), # less than the second (-1), or greater than the second (1). puts 1 <=> 2 puts 1 <=> 1 puts 2 <=> 1 puts '======' # The === test if a value is in a range puts (10...14) === 9 puts (10...14) === 10 puts (10...14) === 12 puts (10...14) === 14 puts (10...14) === 15 puts '======' # Ruby Assignment Operators: # Assignment operators puts '======' x = 37 # assignment puts x += 10 # abbreviated assignment add puts x -= 10 # abbreviated assignment subtract puts x *= 2 # abbreviated assignment multiply puts x /= 2 # abbreviated assignment divide puts x %= 5 # abbreviated assignment modulus puts x **= 3 # abbreviated assignment exponent puts '======' # Ruby Ternary operator: # result = condition ? true_value : false_value toppings = 4 price = toppings > 3 ? 5.99 : 4.99 puts price age = 10 type = age < 18 ? "child" : "adult" puts "You are a " + type # Or... puts "You are a " + (age == 18 ? "child" : "adult") # Ternary operator alternative type = 'child' if age < 18 type = 'adult' unless age < 18 puts "You are a " + type # Ranges as Sequences: (1..5) #==> 1, 2, 3, 4, 5 (1...5) #==> 1, 2, 3, 4 ('a'..'d') #==> 'a', 'b', 'c', 'd' $, =", " # Array value separator range1 = (1..10).to_a range2 = ('bar'..'bat').to_a puts "#{range1}" puts "#{range2}"
true
9d5e61b6b521d98f8b8f49978af7bf2884c8f948
Ruby
Bismarck-GM/using-new-ruby-linters
/launch_school_exercises/001.rb
UTF-8
170
3.375
3
[ "MIT" ]
permissive
# frozen_string_literal: true new_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_array.each do |v| puts v end # Could've used also new_array.each { |value| puts value }
true
76eeae2233f8785ef4282f41ff391bda02e69c78
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/01aecafedee843a4ab09669470a07f5a.rb
UTF-8
326
3.3125
3
[]
no_license
require 'byebug' class Hamming def self.compute(mydna, yourdna) combinedsequence = mydna.chars.zip(yourdna.chars) debugger differencecount = 0 combinedsequence.each{|x,y| if (x != y) && !(x.nil?) && !(y.nil?) differencecount = differencecount + 1 end } differencecount end end
true
5ed8992a3d53c8e4a796532de6d663e2bb99a1b7
Ruby
atalanda/atalogics_api
/examples/example_address_check.rb
UTF-8
1,882
2.65625
3
[ "MIT" ]
permissive
lib = File.expand_path('../../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'atalogics_api' AtalogicsApi.configure do |config| config.client_id = "XXXXXXXXXXXXXXXXXXXXXXXXX" config.client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXX" end # generate a new client client = AtalogicsApi::Client.new access_token = client.access_token puts "access_token: #{access_token}" # refresh your access token access_token = client.refresh_access_token puts "new access_token: #{access_token}" puts "-----------------------------------" # address_check, response is an instance of HTTParty::Response response = client.address_check street: "Ignaz Harrer Str.", number: "12", postal_code: 5020, city: "Salzburg" puts "address_check response:" puts "Code: #{response.code}, parsed_response: #{response.parsed_response}" puts "-----------------------------------" # information about the catch and drop address catch_drop_information = { catch_address: { street: "Ignaz Harrer Str.", number: "12", postal_code: 5020, city: "Salzburg" }, drop_address: { street: "Nonntaler Haupstr.", number: "114", postal_code: 5020, city: "Salzburg" } } # get offers offers = client.offers catch_drop_information puts "offers response:" puts offers offer_id = offers.first["offer_id"] puts "-----------------------------------" # purchase an offer catch_drop_information = { offer_id: offer_id, catch_address: { firstname: "Jane", lastname: "Doe", phone: "1234567890", street: "Ignaz Harrer Str.", number: "12", postal_code: 5020, city: "Salzburg" }, drop_address: { firstname: "John", lastname: "Doe", phone: "1234567890", street: "Nonntaler Haupstr.", number: "114", postal_code: 5020, city: "Salzburg" } } shipment = client.purchase_offer catch_drop_information puts "purchased shipment response:" puts shipment
true
45bf6937bd95e9e8048a243780ae82b45e8c1131
Ruby
elapassarelli/NewElectionSite
/KWK/projects/game_of_swordz/game.rb
UTF-8
429
2.609375
3
[]
no_license
require_relative 'player.rb' JamesBond007 = Player.new("James Bond") JamesBond007.status_report Ela = Player.new("Ela Passarelli") Ela.status_report EvaaUtzz = Player.new("Eva Utz") EvaaUtzz.status_report JamesBond007.attack(Ela) JamesBond007.status_report Ela.status_report Ela.attack() Ela.status_report JamesBond007.status_report Ela.increase_health # methods: # -level_up # -cash_bonus # -status_report # -attack # -increase_health
true
a7fd20f65c552eec236db3b612f379a204c255a5
Ruby
kradul/bewd_sf_12
/05_Classes_Objects/solutions/hw_store_solution/lib/customer.rb
UTF-8
1,690
3.9375
4
[]
no_license
#use this file to define a class that will represent a customer class Customer attr_accessor :name, :money, :shopping_cart def initialize(name, money) @name = name @money = money @shopping_cart = {} end def add_to_cart (store, item, num) #code here #look up the item's price in the store price = store.inventory[item][:price] #make sure to update how many items are in the store #take items away from the store and find out how many we can buy #if you didn't do the bonus step, it's totally fine to just call store.decrease_item(item, num) #and use num in the rest of the code items_bought = store.decrease_item(item, num) #add the items to the customer #check if customer already has the item if @shopping_cart[item] #if customer already has the item, #ADD num more to the amount already in the cart @shopping_cart[item][:quantity] += items_bought else #if they don't have the item, just add the price and quantity info @shopping_cart[item] = {price: price, quantity: items_bought} end puts "#{@name} added #{num} #{item} to his cart. Here is their shopping cart:" puts @shopping_cart.to_s end def checkout(store) #sum up the total cost of all items in the cart #decrease the customer's money #clear the shopping cart (now the items are in the customer's fridge!) total_cost = 0 @shopping_cart.each do |item, hash| total_cost += hash[:price]*hash[:quantity] end if @money > total_cost @money -= total_cost @shopping_cart = {} puts "#{@name} spent #{total_cost} at #{store.name}" else @shopping_cart = {} puts "Insufficient Funds. Your shopping cart has been cleared." end end end
true
d9d263983a654d38976ec9e2f237fa1515787800
Ruby
adamcooke/moonrope
/lib/moonrope/html_generator.rb
UTF-8
2,487
2.546875
3
[ "MIT" ]
permissive
require 'erb' require 'fileutils' require 'moonrope/doc_context' module Moonrope class HtmlGenerator def initialize(base, template_root_path) @base = base @template_root_path = template_root_path end attr_reader :base attr_reader :template_root_path def host ENV['MR_HOST'] end def prefix ENV['MR_PREFIX'] || 'api' end def version ENV['MR_VERSION'] || 'v1' end def generate(output_path) FileUtils.mkdir_p(output_path) FileUtils.cp_r(File.join(@template_root_path, 'assets'), File.join(output_path, 'assets')) FileUtils.touch(File.join(output_path, 'moonrope.txt')) # Index generate_file(output_path, "index.html", "index") # Controllers @base.controllers.select { |c| c.doc != false }.each do |controller| generate_file(output_path, File.join("controllers", "#{controller.name}.html"), "controller", {:controller => controller}) controller.actions.select { |_,a| a.doc != false }.each do |_, action| generate_file(output_path, File.join("controllers", controller.name.to_s, "#{action.name}.html"), "action", {:controller => controller, :action => action}) end end # Structures @base.structures.select { |s| s.doc != false }.each do |structure| generate_file(output_path, File.join("structures", "#{structure.name}.html"), "structure", {:structure => structure}) end # Authenticators @base.authenticators.values.select { |s| s.doc != false }.each do |authenticator| generate_file(output_path, File.join("authenticators", "#{authenticator.name}.html"), "authenticator", {:authenticator => authenticator}) end end private def generate_file(root_dir, output_file, template_file, variables = {}) file = DocContext.new(self, :html_extensions => true, :welcome_file => 'index', :output_file => output_file, :vars => variables) file_string = file.render(File.join(@template_root_path, "#{template_file}.erb")) layout = DocContext.new(self, :html_extensions => true, :welcome_file => 'index', :output_file => output_file, :vars => {:page_title => file.vars[:page_title], :active_nav =>file.vars[:active_nav], :body => file_string}).render(File.join(@template_root_path, "layout.erb")) path = File.join(root_dir, output_file) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') { |f| f.write(layout) } end end end
true
365d61a73543711daab09138cd26468c0943a68e
Ruby
CodingDojoDallas/ruby-oct-2016
/Guerrero_Melissa/animals/mammal.rb
UTF-8
206
3.671875
4
[]
no_license
class Mammal attr_accessor :alive, :health def initialize(alive, health) @alive=True puts "I am alive!" @health=150 self end def display_health puts "The health score is #{@health}." end end
true
e59cbde4180e29b47c0fb023db492b05f2fb1f93
Ruby
firrds/DXRuby-Game-Tutorial
/answer/q1-1.rb
UTF-8
947
3.125
3
[]
no_license
# coding: utf-8 require 'dxruby' x = 400 y = 0 image = Image.load_tiles("./character.png", 4, 4) # Sprite.new とはゲーム上でキャラクタを扱う為に使用するメソッドで、 # このメソッドによって作られたデータを使うことで、 # キャラクタの位置の変更や衝突の判定を簡単に行うことが出来る sample_sprite = Sprite.new(x, y, image[0]) Window.loop do # sample_sprite という Sprite データの x 座標をプラス 1 する # += という記号の組み合わせは、左辺の値に右辺の値をプラスし、代入する意味を持つ # 他にも、-=, *=, /= などもある # += 1 の場合だと左辺の変数の値が 1 ずつ増加していく sample_sprite.x -= 1 # Sprite.draw メソッドを使うと指定した Sprite データを画面に表示 (描画) することが出来る Sprite.draw(sample_sprite) end
true
65895039fe7be44c57f8e6df66341d002c982333
Ruby
standevenjw/euler
/project21.rb
UTF-8
433
3.703125
4
[]
no_license
#Project 21 from projecteuler.net #Evaluate the sum of all the amicable numbers under 10000 #Coded by: James Standeven #!/usr/bin/env ruby arr = [0, 1] sum = 0 top = 10000 def divisors n list = [] m = 1 while m <= n/2 if n % m == 0 list << m end m += 1 end list end 0.upto(top){|c| arr[c] = divisors(c).inject(0, :+)} 2.upto(top) do |x| if x == arr[arr[x]] && x != arr[x] sum += x end end puts sum
true
94600b783a72da02634607438932378ba6b09250
Ruby
12Starlight/App-Academy-Master
/Immersive/W6D3/Paired Exercise/Chess/board.rb
UTF-8
2,755
3.71875
4
[]
no_license
require_relative 'pieces' require "byebug" class Board attr_reader :grid def initialize @grid = Array.new(8) { Array.new(8)} # Setup nullpieces (2..5).each do |row| (0..7).each do |col| @grid[row][col] = NullPiece.instance end end # Setup pawns (0..7).each do |col| @grid[1][col] = Pawn.new(:red) @grid[6][col] = Pawn.new(:yellow) end # Setup kings @grid[0][3] = King.new(:red) @grid[7][3] = King.new(:yellow) # Setup queens @grid[0][4] = Queen.new(:red) @grid[7][4] = Queen.new(:yellow) # Setup bishops @grid[0][2] = Bishop.new(:red) @grid[0][5] = Bishop.new(:red) @grid[7][2] = Bishop.new(:yellow) @grid[7][5] = Bishop.new(:yellow) # Setup knights @grid[0][1] = Knight.new(:red) @grid[0][6] = Knight.new(:red) @grid[7][1] = Knight.new(:yellow) @grid[7][6] = Knight.new(:yellow) # Setup rooks @grid[0][0] = Rook.new(:red) @grid[0][7] = Rook.new(:red) @grid[7][7] = Rook.new(:yellow) @grid[7][0] = Rook.new(:yellow) end def [](pos) x, y = pos @grid[x][y] end def []=(pos, value) x, y = pos @grid[x][y] = value end def valid_pos?(pos) # => [x, y] x, y = pos x.between?(0, 7) && y.between?(0, 7) end def move_piece(color, start_pos, end_pos) # raise "There is no piece at start position" # raise "The peice cannot move to end_pos" # Set if statements for non-valid moves and no-piece start_pos # non-valid moves : valid_pos? / end_pos same color as start_pos / begin if start_pos == end_pos raise NoPieceHereError end if !valid_pos?(end_pos) || self[start_pos].color == self[end_pos].color raise CannotMoveHereError end self[end_pos] = self[start_pos] self[start_pos] = NullPiece.instance rescue NoPieceHereError => exception exception.message rescue CannotMoveHereError => exception exception.message end end def display (0..7).each do |row| (0..7).each do |col| print "#{@grid[row][col].symbol} | " end puts end end end class CannotMoveHereError < StandardError def message puts "You can not move here silly :)" end end class NoPieceHereError < StandardError def message puts "There is no piece to move" end end # =begin # Notes: # * .between - Returns false if obj <=> min is less than zero or if anObject <=> max is greater than zero, true otherwise. # end
true
ec5bd7f59bcede300ae7e97d49bbb3a1ac2456d6
Ruby
VanessaVViana/TestesUnitarios-RubyRspec
/unitarios/spec/bank/saque_cp_spec.rb
UTF-8
1,707
2.796875
3
[]
no_license
require_relative '../../app/bank' describe ContaPoupanca do describe 'Saque' do context 'Quando o valor é positivo' do before(:all) do @cp = ContaPoupanca.new(1000.00) @cp.saca(200.00) end it 'entao atualiza saldo' do expect(@cp.saldo).to eql 798.00 end end context 'Quando não tenho saldo' do before(:all) do @cp = ContaPoupanca.new(0.00) @cp.saca(100.00) end it 'sistema exibe mensagem' do expect(@cp.mensagem).to eql 'Saldo insuficiente para saque :(' end it 'então meu saldo permanece' do expect(@cp.saldo).to eql 0.00 end end context 'Tenho saldo mas não o suficiente' do before(:all) do @cp = ContaPoupanca.new(500.00) @cp.saca(501.00) end it 'sistema exibe mensagem' do expect(@cp.mensagem).to eql 'Saldo insuficiente para saque :(' end it 'então meu saldo permanece' do expect(@cp.saldo).to eql 500.00 end end context 'Limite por Saque :(' do before(:all) do @cp = ContaPoupanca.new(1000.00) @cp.saca(701.00) end it 'sistema exibe mensagem' do expect(@cp.mensagem).to eql 'Limite máximo por saque é de R$ 500' end it 'então meu saldo permanece' do expect(@cp.saldo).to eql 1000.00 end end end end
true
bcd07473a3faa0eea58ddb5f6cfadcb41fa39fed
Ruby
ardnek/parsing-http
/lib/parse_request.rb
UTF-8
1,436
3.34375
3
[]
no_license
# write your code here http_request = File.read('../data/get_request.txt').split("\n") #blueprint class Request attr_accessor :request def http_verb @request[0].split(" ")[0] end def version @request[0].split(" ")[2] end def path @request[0].split(" ")[1].split("?")[0] end def query_params @param_hash = {} @param_array = @request[0].split(" ")[1].split("?")[1].split("&") @param_hash[@param_array[0].split("=")[0].to_sym] = @param_array[0].split("=")[1] @param_hash[@param_array[1].split("=")[0].to_sym] = @param_array[1].split("=")[1] @param_hash[@param_array[2].split("=")[0].to_sym] = @param_array[2].split("=")[1] end def query_string @param_array = @request[0].split(" ")[1].split("?")[1].split("&") end def body @body_hash = {} @body_hash[@request[1].split(" ")[0].chop.to_sym] = @request[1].split(" ")[1] @body_hash[@request[2].split(" ")[0].chop.to_sym] = @request[2].split(" ")[1] @body_hash[@request[3].split(" ")[0].chop.to_sym] = @request[3].split(" ")[1] @body_hash end def params self.query_params.merge(self.body) end end testclass = Request.new testclass.request = http_request p testclass.body # string = "Stephen Kendra Turek Prill" # # kendraclass = Request.new # kendraclass.request = string.split(" ") # puts kendraclass.http_verb # attr_accessor # def yo # @yo # end # # def yo=(something) # @yo=something # end
true
2fff1dd6315ee509021c90cf247a4410c399a3df
Ruby
wallacerunner/ruby_code_dump
/kata/ipv4toint32.rb
UTF-8
516
3.125
3
[]
no_license
# Take IPv4 address, convert every octet of it to binary, join and covert the # result into an integer def ip_to_int32(ip) ip.split('.').map { |octet| octet.to_i.to_s(2). prepend('0' * (8 - octet.to_i.to_s(2).length)) }.join.to_i(2) end require 'ipaddr' def ip_to_int32_require(ip) x = IPAddr.new(ip).to_i end def ip_to_int32_reduce(ip) ip.split( '.' ).reduce( 0 ) { |total, p| total * 256 + p.to_i } end def ip_to_int32_division(ip) ("%02x%02x%02x%02x" % ip.split('.')).to_i(16) end
true
3356ff6f800eedb4bd5e180a5bb1f256e530efc1
Ruby
bbensky/pine_ruby_exercises
/chris_pine_ex/ch9_classes.rb
UTF-8
4,491
3.828125
4
[]
no_license
=begin a = Array.new + [12345] b = String.new + 'hello' c = Time.new puts 'a = ' + a.to_s puts 'b = ' + b.to_s puts 'c = ' + c.to_s time = Time.new time2 = time + 60 puts time puts time2 ≈ puts Time.mktime(2000, 1, 1) puts Time.mktime(1976, 8, 3, 10, 11) puts Time.mktime(1979, 5, 27) - Time.mktime(1976, 8, 2) colorArray = [] colorHash = {} colorArray[0] = 'red' colorArray[1] = 'green' colorArray[2] = 'blue' colorHash['strings'] = 'red' colorHash['numbers'] = 'green' colorHash['keywords'] = 'blue' colorArray.each do |color| puts color end colorHash.each do |codeType, color| puts codeType + ': ' + color end weirdHash = Hash.new weirdHash[12] = 'monkeys' weirdHash[[]] = 'emptiness' weirdHash[Time.new] = 'no time like the preset' puts weirdHash class Integer def to_eng if self == 5 english = 'five' else english = 'fifty-eight' end english end end puts 5.to_eng puts 58.to_eng class Die def roll 1 + rand(6) end end dice = [Die.new, Die.new] dice.each do |die| puts die.roll end class Die def roll @numberShowing = 1 + rand(6) end def showing @numberShowing end end die = Die.new die.roll puts die.showing puts die.showing die.roll puts die.showing puts die.showing class Die def roll @numberShowing = 1 + rand(6) end def showing @numberShowing end end puts Die.new.showing class Die def initialize roll end def roll @numberShowing = 1 + rand(6) end def showing @numberShowing end end puts Die.new.showing class Die def initialize roll end def roll @numberShowing = 1 + rand(6) end def showing @numberShowing end def cheat number @numberShowing = number end end puts "What number would you like the die to have?" number = gets.chomp.to_i if number > 6 puts 'The number must be less than 6.' number = gets.chomp end dice = Die.new dice.cheat number puts dice.showing =end class Dragon def initialize name @name = name @asleep = false @stuffInBelly = 10 # He's full. @stuffInIntestine = 0 # He doesn't need to go. puts @name + ' is born.' end def feed puts 'You feed ' + @name + '.' @stuffInBelly = 10 passageOfTime end def walk puts 'You walk ' + @name + '.' @stuffInIntestine = 0 passageOfTime end def putToBed puts 'You put ' + @name + ' to bed.' @asleep = true 3.times do if @asleep passageOfTime end if @asleep puts @name + ' snores, filling the room with smoke.' end end if @asleep @asleep = false puts @name + ' wakes up slowly.' end end def toss puts 'You toss ' + @name + ' up into the air.' puts 'He giggles, which singes your eyebrows.' passageOfTime end def rock puts 'You rock ' + @name + ' gently.' @asleep = true puts 'He briefly dozes off...' passageOfTime if @asleep @asleep = false puts '...but wakes when you stop.' end end private # "private" means that the methods defined here are # methods internal to the object. (You can feed # your dragon, but you can't ask him if he's hungry.) def hungry? # Method names can end with "?". # Usually, we only do this if the method # returns true or false, like this: @stuffInBelly <= 2 end def poopy? @stuffInIntestine >= 8 end def passageOfTime if @stuffInBelly > 0 # Move food from belly to intestine. @stuffInBelly = @stuffInBelly - 1 @stuffInIntestine = @stuffInIntestine + 1 else # Our dragon is starving! if @asleep @asleep = false puts 'He wakes up suddenly!' end puts @name + ' is starving! In desperation, he ate YOU!' exit # This quits the program. end if @stuffInIntestine >= 10 @stuffInIntestine = 0 puts 'Whoops! ' + @name + ' had an accident...' end if hungry? if @asleep @asleep = false puts 'He wakes up suddenly!' end puts @name + '\'s stomach grumbles...' end if poopy? if @asleep @asleep = false puts 'He wakes up suddenly!' end puts @name + ' does the potty dance...' end end end pet = Dragon.new 'Norbert' pet.feed pet.toss pet.walk pet.putToBed pet.rock pet.putToBed pet.putToBed pet.putToBed pet.putToBed
true
d3785c9c3f261802a8e5e49ce687b4582c7732a8
Ruby
dsawardekar/riml
/test/integration/riml_commands/compiler_test.rb
UTF-8
6,516
2.640625
3
[ "MIT" ]
permissive
require File.expand_path('../../../test_helper', __FILE__) class RimlCommandsCompilerTest < Riml::TestCase test "riml_source raises error if the file is not in Riml.source_path" do riml = <<Riml riml_source "nonexistent_file.riml" Riml assert_raises Riml::FileNotFound do compile(riml) end end test "riml_include raises error if the file is not in Riml.source_path" do riml = <<Riml riml_include "nonexistent_file.riml" Riml assert_raises Riml::FileNotFound do compile(riml) end end test "riml_source compiles and sources file if file exists in Riml.source_path" do riml = <<Riml riml_source "file1.riml" Riml expected = <<Viml source file1.vim Viml cwd = File.expand_path("../", __FILE__) with_riml_source_path(cwd) do Dir.chdir(cwd) do with_file_cleanup("file1.vim") do assert_equal expected, compile(riml) file1_vim = File.join(Riml.source_path.first, "file1.vim") assert File.exists?(file1_vim) assert_equal Riml::FILE_HEADER + File.read("./file1_expected.vim"), File.read(file1_vim) end end end end test "files sourced from the main file have access to the classes created in the main file" do riml = <<Riml class Car def initialize(*args) self.maxSpeed = 100 self.options = args end end riml_source 'faster_car.riml' Riml expected = <<Viml function! g:CarConstructor(...) let carObj = {} let carObj.maxSpeed = 100 let carObj.options = a:000 return carObj endfunction source faster_car.vim Viml cwd = File.expand_path("../", __FILE__) with_riml_source_path(cwd) do Dir.chdir(cwd) do with_file_cleanup("faster_car.vim") do assert_equal expected, compile(riml) assert File.exists?("faster_car.vim") assert_equal Riml::FILE_HEADER + File.read("faster_car_expected.vim"), File.read("faster_car.vim") end end end end test "riml_source raises ClassNotFound if the sourced file references undefined class" do riml = <<Riml riml_source 'faster_car.riml' Riml with_riml_source_path(File.expand_path("../", __FILE__)) do with_file_cleanup("faster_car.vim") do assert_raises Riml::ClassNotFound do compile(riml) end end end end test "riml_include #includes the compiled output of the included file inline in the code" do riml = <<Riml riml_include 'file1.riml' class Car def initialize(*args) self.maxSpeed = 100 self.options = args end end Riml expected = <<Viml " included: 'file1.riml' echo "hi" function! g:CarConstructor(...) let carObj = {} let carObj.maxSpeed = 100 let carObj.options = a:000 return carObj endfunction Viml with_riml_include_path(File.expand_path("../", __FILE__)) do assert_equal expected, compile(riml) faster_car_vim = File.join(Riml.include_path.first, "faster_car.vim") refute File.exists?(faster_car_vim) end end test "riml_include raises ClassNotFound if class referenced in included file is undefined" do riml = "riml_include 'faster_car.riml'" with_riml_include_path(File.expand_path("../", __FILE__)) do assert_raises(Riml::ClassNotFound) do compile(riml) end end end test "riml_include is recursive" do riml = "riml_include 'riml_include_lib.riml'" expected = <<Riml " included: 'riml_include_lib.riml' " included: 'riml_include_lib2.riml' function! g:Lib2Constructor() let lib2Obj = {} return lib2Obj endfunction function! g:Lib1Constructor() let lib1Obj = {} let lib2Obj = g:Lib2Constructor() call extend(lib1Obj, lib2Obj) return lib1Obj endfunction Riml with_riml_include_path(File.expand_path("../", __FILE__)) do assert_equal expected, compile(riml) end end test "riml_include doesn't get stuck in infinite loop when two files include each other" do riml = %Q(riml_include 'riml_include_loop1.riml' " loop1 includes loop2 which includes loop1...) expected = <<Viml " included: 'riml_include_loop1.riml' " included: 'riml_include_loop2.riml' Viml with_riml_include_path(File.expand_path("../", __FILE__)) do assert_equal expected, compile(riml) end end test "riml_include raises error when including itself" do riml = %Q(riml_include 'riml_include_self.riml') with_riml_include_path(File.expand_path("../", __FILE__)) do assert_raises(Riml::UserArgumentError) do compile(riml) end end end test "riml_include raises error if not called from top-level" do riml = <<Riml if includeFile1 riml_include 'file1.riml' end Riml assert_raises(Riml::IncludeNotTopLevel) do compile(riml) end end test "riml_source raises ArgumentError if argument not a string" do riml = "riml_source file" assert_raises(Riml::UserArgumentError) do compile(riml) end riml2 = "riml_source" assert_raises(Riml::UserArgumentError) do compile(riml2) end end test "riml_include raises ArgumentError if argument not a string" do riml = "riml_include file" assert_raises(Riml::UserArgumentError) do compile(riml) end riml2 = "riml_include" assert_raises(Riml::UserArgumentError) do compile(riml2) end end test "riml_source only compiles a sourced file once per compilation process, across all files that reference each other" do riml = <<RIML riml_source 'sourced1.riml' RIML expected = "source sourced1.vim\n" with_riml_source_path(File.expand_path("../", __FILE__)) do with_file_cleanup('sourced1.vim', 'sourced2.vim') do assert_equal expected, compile(riml) assert File.exists?(File.join(Riml.source_path.first, 'sourced1.vim')) assert File.exists?(File.join(Riml.source_path.first, 'sourced2.vim')) end end end test "Riml.source_path looks up files in source_path order and riml_source outputs them in proper directory" do riml = <<RIML riml_source 'sourced1.riml' RIML expected = "source sourced1.vim\n" with_riml_source_path(File.expand_path("../test_source_path", __FILE__), File.expand_path("../", __FILE__)) do with_file_cleanup('sourced2.vim', 'sourced1.vim') do assert_equal expected, compile(riml) assert File.exists?(File.join(Riml.source_path.first, 'sourced2.vim')) # in test_source_path dir assert File.exists?(File.join(Riml.source_path[1], 'sourced1.vim')) end end end end
true
e6199cc5a75067ebc9e15999f7a929c26d8a377e
Ruby
almalee24/school-domain-onl01-seng-ft-081720
/lib/school.rb
UTF-8
464
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School attr_reader :roster, :school_name, :student_name def initialize(school_name) @school_name = school_name @roster = {} end def add_student(student_name, grade) if @roster[grade] @roster[grade] << student_name else @roster[grade] = [] @roster[grade] << student_name end end def grade(grade) @roster[grade] end def sort @roster.each{|k, v| v.sort!} @roster.sort.to_h end end
true
d5ba411b3c01aeb9ec21bf296ff63a195a0ff3c8
Ruby
learn-co-students/web-060517
/quizzes/customer.rb
UTF-8
287
3.171875
3
[]
no_license
class Customer attr_writer :name attr_reader :name def initialize(name, hometown) @name = name @hometown = hometown end def name @name end def foo self.name end end customer = Customer.new customer.name = 'bob' customer.name -> "bob" <@name="bob">
true
91d5d8b6f37f2eae29f6d2dc88e2ca11d4fb86b2
Ruby
ehrenmurdick/space
/src/states/warp.rb
UTF-8
2,144
2.703125
3
[]
no_license
require 'yaml' require './src/obj/npc' class Warp < Chingu::GameState traits :viewport, :timer attr_accessor :player attr_reader :danger, :song def initialize(old_system, new_system) super() @old_system = YAML.load(File.read("data/systems.yml"))[old_system] @new_name = new_system @new_system = YAML.load(File.read("data/systems.yml"))[new_system] $danger = Gosu::Song["assets/music/danger.wav"] @song = Gosu::Song["assets/music/planet2.wav"] $state = self @song.play(true) # # Player will automatically be updated and drawn since it's a Chingu::GameObject # You'll need your own Chingu::Window#update and Chingu::Window#draw after a while, but just put #super there and Chingu can do its thing. # self.viewport.game_area = [0, 0, 10_000, 10_000] @player = Player.create @player.x = 4500 @player.y = 4500 @player.angle = 0 @player.zorder = 200 $player = @player @bg = Bg.create @bg.image = Gosu::Image["assets/warp.png"] end def button_down(id) exit if id == Gosu::Button::KbQ end def setup dist = Gosu.distance(@old_system["x"], @old_system["y"], @new_system["x"], @new_system["y"]) after((dist/@player.warp_speed)*50) do new_state = Space.new(@new_name) new_state.player.x = 640 new_state.player.y = 480 new_state.player.velocity_x = @player.velocity_x new_state.player.velocity_y = @player.velocity_y new_state.player.angle = @player.angle new_state.player.ship = @player.ship new_state.player.thruster = false new_state.player.fuel = @player.fuel - dist $window.switch_game_state(new_state) end end def update super if @player.x > 10_000 - 640 @player.x = 640 elsif @player.x < 640 @player.x = 10_000 - 640 end if @player.y > 10_000 - 480 @player.y = 480 elsif @player.y < 480 @player.y = 10_000 - 480 end viewport.center_around(@player) @bg.x = ((@player.x / 640.0).floor * 640) + (@player.x * 0.2) % 640 @bg.y = ((@player.y / 480.0).floor * 480) + (@player.y * 0.2) % 480 end end
true
af485a82561d28e5de6a4f49f19ab796d87ffefd
Ruby
arathunku/rulsp
/count.rb
UTF-8
53
2.5625
3
[]
no_license
puts ARGV[0].to_i.times.inject(0) { |acc| acc + 1 };
true
74db6d81fadf15c28d4f725780a3c7103dd2c209
Ruby
Geek24/ruby_practice
/polymorphism.rb
UTF-8
431
4.03125
4
[]
no_license
# Practice for how polymorphism works in Ruby class Bird def tweet(bird_type) bird_type.tweet # calling its version of tweet here end end class Cardinal < Bird #inherit from bird def tweet puts "Tweet" end end class Parrot < Bird def tweet puts "Squawk" end end generic_bird = Bird.new # Below we see polymorphism generic_bird.tweet(Cardinal.new) generic_bird.tweet(Parrot.new)
true
bcd96a832d93ae09212b654aa14298332d97ea66
Ruby
Nilsyy/reinforcements
/bonus.rb
UTF-8
623
3.28125
3
[]
no_license
documentary = "Cowspiracy" drama = "Riverdale" comedy = "Mr. Bean" dramedy = "Glee" puts "On a scale of 1-5, rate documentaries:" documentary_answer = gets.to_i puts "On a scale of 1-5, rate dramas:" drama_answer = gets.to_i puts "On a scale of 1-5, rate comedies:" comedy_answer = gets.to_i if documentary_answer > 3 elsif drama_answer > 3 && comedy_answer > 3 puts "I reccommend you watch #{dramedy}!" elsif drama_answer > 3 puts "I reccommend you watch #{drama}!" elsif comedy_answer > 3 puts "I reccommend you watch #{comedy}!" else puts "You are of no use to me any longer, go and read Twilight!" end
true
cfe3658390556810a03cf13725f6c0b838a418a8
Ruby
miura1729/mruby-meta-circular
/sample/pjson.rb
UTF-8
5,898
3.296875
3
[]
no_license
class Array def each(&block) return to_enum :each unless block idx = 0 while idx < length block.call(self[idx]) idx += 1 end self end end class Context WHITE_SPACES = [" ", "\t", "\r", "\n"] NUMBER_LETTERS = '0123456789+-.eE' HEX_LETTERS = '0123456789abcdef' def initialize(s) @buf = s @index = 0 @length = s.size end def skip_white while [" ", "\t", "\r", "\n"].include? @buf[@index] do @index += 1 end $foo = @index end def has_next? @index < @length end def next b = @buf[@index] @index += 1 b end def back @index -= 1 end def current return @buf[@index] end def error(msg) raise "#{msg}: #{@buf[@index...-1]}" end def parse_constant(expect, value) s = '' pos = @index while self.has_next? c = self.next unless expect.include? c if s == expect self.back return value end @index = pos error 'Unknown token' end s += c end error 'Unknown token' end def parse_number s = self.next while self.has_next? c = self.next unless '0123456789+-.eE'.include? c self.back break end s += c end if s.include? '.' return s.to_f end return s.to_i end def parse_string self.next s = '' while self.has_next? c = self.next case c when '\\' c = self.next case c when '\\', '/' s += c when 'b' s += "\b" when 'f' s += "\f" when 'n' s += "\n" when 'r' s += "\r" when 't' s += "\t" when 'u' u = 0 while self.has_next? c = self.next c0 = c.downcase i = '0123456789abcdef'.index(c0) # if i == nil if i.nil? self.back break end u = u * 16 | i end if u < 0x80 s += u.chr elsif u < 0x800 s += (0xc0 | (u >> 6)).chr s += (0x80 + (u & 0x3f)).chr elsif u < 0x10000 s += (0xe0 | (u >> 12)).chr s += (0x80 | ((u >> 6) & 0x3f)).chr s += (0x80 | (u & 0x3f)).chr elsif u < 0x200000 s += (0xf0 | (u >> 18)).chr s += (0x80 | ((u >> 12) & 0x3f)).chr s += (0x80 | ((u >> 6) & 0x3f)).chr s += (0x80 | (u & 0x3f)).chr elsif u < 0x4000000 s += (0xf8 | (u >> 24)).chr s += (0x80 | ((u >> 18) & 0x3f)).chr s += (0x80 | ((u >> 12) & 0x3f)).chr s += (0x80 | ((u >> 6) & 0x3f)).chr s += (0x80 | (u & 0x3f)).chr else s += (0xfc | (u >> 30)).chr s += (0x80 | ((u >> 24) & 0x3f)).chr s += (0x80 | ((u >> 18) & 0x3f)).chr s += (0x80 | ((u >> 12) & 0x3f)).chr s += (0x80 | ((u >> 6) & 0x3f)).chr s += (0x80 | (u & 0x3f)).chr end else error 'Invalid string token' end when '"' return s else s += c end end error 'Invalid string token' end def parse_object self.next o = {} while self.has_next? self.skip_white c = self.next if c == '}' self.next break end if c != '"' error 'Expected "\"" but not found' end self.back k = self.parse_string self.skip_white c = self.next if c != ':' error 'Expected ":" but not found' end self.skip_white v = self.parse_value o[k] = v self.skip_white c = self.current if c == '}' self.next break end if c != ',' error 'Expected "," or "}" but not found' end self.next end o end def parse_array self.next a = [] while self.has_next? self.skip_white if self.current == ']' break end i = self.parse_value self.skip_white c = self.next a << i if c == ']' break end if c != ',' error 'Expected "," or "]" but not found' end end a end def parse_value self.skip_white c = self.current case c when '{' return self.parse_object when '[' return self.parse_array when '"' return self.parse_string when '0','1','2','3','4','5','6','7','8','9','-' return self.parse_number when 't' return self.parse_constant('true', true) when 'f' return self.parse_constant('false', false) when 'n' return self.parse_constant('null', nil) else error 'Invalid sequence' end end end def parse(text) Context.new(text).parse_value end def top 10000.times do p parse('{"foo": "bar"}') # p parse('{"foo": "baz", "abc": "abaz"}') # p parse('[true, "foo"]') # p parse('{"label":[true, "foo"]}') # p parse('[true, {"foo" : "bar"}]') # p parse('[1, {"2.0" : 3.0}]') end end MTypeInf::inference_main { top }
true
c0e1ece91414db17fa5912b59d9467f3190ff95a
Ruby
MaryCrisEstudillo/Ruby-Activities
/rubyactivities/abstraction.rb
UTF-8
1,264
4.03125
4
[]
no_license
class Transaction def initialize puts "What do you want to do?" chooseTransac = gets.chomp if chooseTransac == "deposit" puts "Enter Deposit Amount:" @deposit = gets.chomp.to_i @currentMoney = 200 deposit_amount elsif chooseTransac == "withdraw" puts "Enter Withdraw Amount:" @withdraw = gets.chomp.to_i @currentMoney = 200 withdraw_amount elsif chooseTransac == "transfer" puts "Enter Transfer Amount:" @transfer = gets.chomp.to_i @currentMoney = 200 transfer_amount else puts "input error! please enter either deposit, withdraw or transfer word only" end end private def deposit_amount puts "You deposited #{@deposit} in your account. Your current balance is #{@deposit + @currentMoney}" end def withdraw_amount puts "You Withdraw #{@withdraw} in your account. Your current balance is #{@currentMoney - @withdraw}" end def transfer_amount puts "you transfer #{@transfer} in other account. Your current balance is #{@currentMoney - @transfer}" end end Transaction.new
true
b52a44f12d470fda01714fefec7a0ce22a46c8d3
Ruby
skellock/sugarcube
/spec/uiimage_spec.rb
UTF-8
16,493
2.640625
3
[ "BSD-2-Clause" ]
permissive
describe 'UIImage' do describe 'UIImage.canvas' do it 'should create an image' do UIImage.canvas(size: [10, 10]).should.is_a UIImage end it 'should have the right size' do CGSizeEqualToSize(UIImage.canvas(size: [10, 10]).size, [10, 10]).should == true end it 'should return width' do image = UIImage.canvas(size: [10, 10]) image.width.should == 10 end it 'should return height' do image = UIImage.canvas(size: [10, 10]) image.height.should == 10 end it 'should have the right scale' do UIImage.canvas(size: [10, 10], scale: 2).scale.should == 2 end describe 'should have the right opacity' do it "should be opaque" do image = UIImage.canvas(size: [10, 10], scale: 2, opaque: true) image.color_at([0, 0]).alpha.should == 1 end it "should be clear" do image = UIImage.canvas(size: [10, 10], scale: 2, opaque: false) image.color_at([0, 0]).alpha.should == 0 end end it 'should draw an image' do image = UIImage.canvas(size: [10, 10], scale: 2) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end image.color_at([0, 0]).should == :red.uicolor end end describe '`<<` method should combine two images' do before do red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end blue = UIImage.canvas(size: [10, 10]) do |context| :blue.uicolor.set CGContextAddRect(context, [[1, 1], [8, 8]]) CGContextFillPath(context) end @img = (red << blue) end it 'should be red in the UL corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should be blue in the UL-inset corner' do @img.color_at([1, 1]).should == :blue.uicolor end it 'should be blue in the BR-inset corner' do @img.color_at([8, 8]).should == :blue.uicolor end it 'should be red in the BR corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe '`merge` method should combine images' do describe 'should merge at top_left' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :top_left) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :blue.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :blue.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :blue.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at top' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :top) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :blue.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at top_right' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :top_right) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :blue.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :blue.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :blue.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at left' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :left) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :blue.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at center' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :center) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at right' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :right) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :blue.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :red.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at bottom_left' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :bottom_left) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :blue.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :blue.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :blue.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at bottom' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :bottom) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :red.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :blue.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :red.uicolor end end describe 'should merge at bottom_right' do before do @red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end @blue = UIImage.canvas(size: [8, 8]) do |context| :blue.uicolor.set CGContextAddRect(context, [[0, 0], [8, 8]]) CGContextFillPath(context) end @img = @red.merge(@blue, at: :bottom_right) end it 'should work at top left corner' do @img.color_at([0, 0]).should == :red.uicolor end it 'should work at top center' do @img.color_at([4, 0]).should == :red.uicolor end it 'should work at top right corner' do @img.color_at([9, 0]).should == :red.uicolor end it 'should work at left side' do @img.color_at([0, 4]).should == :red.uicolor end it 'should work at center' do @img.color_at([4, 4]).should == :blue.uicolor end it 'should work at right side' do @img.color_at([9, 4]).should == :blue.uicolor end it 'should work at bottom left corner' do @img.color_at([0, 9]).should == :red.uicolor end it 'should work at bottom center' do @img.color_at([4, 9]).should == :blue.uicolor end it 'should work at bottom right corner' do @img.color_at([9, 9]).should == :blue.uicolor end end end describe '`overlay` should add shading to an image' do it 'should return an image' do red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end red.overlay(:white).should.is_a?(UIImage) end it 'should return an image that is the same size' do red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end overlay = red.overlay(:white) overlay.size.width.should == red.size.width overlay.size.height.should == red.size.height end it 'should return an image that is a different color' do red = UIImage.canvas(size: [10, 10]) do |context| :red.uicolor.set CGContextAddRect(context, [[0, 0], [10, 10]]) CGContextFillPath(context) end overlay = red.overlay(:white) overlay.color_at([0, 0]).should != red.color_at([0, 0]) end end end
true
52770c05042313ace28e222880f4425afe301bbb
Ruby
deborahleehamel/exercism
/ruby/sieve/sieve.rb
UTF-8
292
2.90625
3
[]
no_license
class Sieve def initialize(limit) @limit = limit end def primes range = (2..@limit).to_a numbers = [] while range.any? numbers << (pick = range.shift) range.reject! { |n| n % pick == 0 } end numbers end end module BookKeeping VERSION = 1 end
true
a9d247249f553a8702e63d726885198dfc6beee3
Ruby
vnqthai/railway-system
/lib/railway/models/line_station.rb
UTF-8
670
3.40625
3
[]
no_license
# A connection between Line and Station # Store information represents this Line-Station connection: # - line: Line object. See line.rb. # - station: Station object. See station.rb. # - number: station number (1, 2, 32, etc.) # - open_at: date of opening, can be in the past or in the future class LineStation attr_accessor :line, :station, :number, :open_at def initialize(line, station, number, open_at) @line = line @station = station @number = number @open_at = open_at end def code "#{@line.code}#{number}" end def open?(time) time >= @open_at && !(@line.close_at_night_time? && TimeService.night_time?(time)) end end
true
82dde1a0972475e75cd604f315c0bc7ae3e2b5bd
Ruby
MASisserson/rb101
/lesson_3/easy_1/1.rb
UTF-8
175
3.90625
4
[]
no_license
# Question 1 numbers = [1, 2, 2, 3] numbers.uniq puts numbers # The above code should print: # 1 # 2 # 2 # 3 # #uniq! is mutating. #uniq is not. numbers remains the same.
true
36aed5a048d9aa1517efb91ac06245b271605f59
Ruby
soimort/pi
/pi
UTF-8
19,655
2.578125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # coding: utf-8 """ pi -- A simple pandoc wrapper that does the trick URL: https://github.com/soimort/pi Author: Mort Yao <[email protected]> Dependencies: - ruby >= 2.2 - listen ~> 3.0 - pandoc >= 1.15 """ require 'date' require 'logger' require 'open3' require 'optparse' require 'webrick' require 'yaml' require 'listen' Version = '3.14' $Patterns = { :general => /^[^_]/, :config => /^_/, :metadata => /\.(yaml|yml)$/, :source => /\.(markdown|md|md\.txt)$/, :bibliography => /\.(bib)$/, } # List all files/directories in a path. def list_files(name = '.', recursive = false, exclude = nil) # check for existence return { :files => [] } unless File.exist? name # is a file return { :files => [name] } unless File.directory? name # is a directory init_result = { :files => [], :directories => [] } Dir.glob(File.join(name, '*')).inject init_result do |result, item| if exclude.is_a?(Regexp) && exclude.match(File.basename(item)) # excluded pattern result elsif File.directory? item # is a directory if recursive { :files => result[:files] + list_files(item, recursive = recursive, exclude = exclude)[:files], :directories => result[:directories] } else { :files => result[:files], :directories => result[:directories] + [item] } end else # is a file { :files => result[:files] + [item], :directories => result[:directories] } end end end # Load configuration from a path. def load_config(name = '.', init_metadata = {}) metadata = init_metadata config = list_files(name, recursive = false, exclude = $Patterns[:general]) config[:directories].each do |name| metadata = load_config(name, init_metadata = metadata) end config[:files].inject metadata do |metadata, file| next metadata unless $Patterns[:metadata].match file tmp = YAML.load_file file if tmp # save full path of loaded config file to metadata (for future use) file = File.expand_path file if metadata[:files].nil? metadata[:files] = [file] elsif !metadata[:files].include?(file) metadata[:files] << file end tmp.merge! metadata else metadata end end end # Load configuration from a path and all its parents to the current path. def load_config_all(name = '.', init_metadata = {}) metadata = {} start_path = $CurPath path = end_path = File.directory?(name) ? File.expand_path(name) : File.expand_path('..', name) metadata = load_config(path, init_metadata = metadata) until path.length <= start_path.length do path = File.expand_path('..', path) metadata = load_config(path, init_metadata = metadata) end metadata.merge! init_metadata end # Get the relative name of path1 under some path2. def get_relative_name(path1, path2) path1.start_with?(path2) && path1 != path2 ? path1[path2.length+1..-1] : "" end # Convert a source file. (synchronous) # Return: exit status of the converter process. def make(source, init_metadata = {}, preload = true, options = {}, logger = Logger.new(STDERR)) metadata = init_metadata if source.is_a? String and File.directory? source metadata = load_config_all(source, init_metadata = metadata) if preload sources = list_files(source, recursive = false, exclude = $Patterns[:config]) sources[:files].each do |source| # skip if not agree with the specified source file name next if !metadata['source'].nil? && metadata['source'] != File.basename(source) # skip if incorrect source file pattern next if !$Patterns[:source].match(source) # make each file make(source, init_metadata = metadata, preload = preload, options = options, logger = logger) end if options[:recursive] sources[:directories].each do |source| # make each subdir recursively make(source, init_metadata = metadata, preload = preload, options = options, logger = logger) end end else # is (at most) a file if source.nil? source_dir = File.expand_path('.') else source_dir = File.expand_path('..', source) end metadata = load_config_all(source_dir, init_metadata = metadata) if preload # check source file extension unless $Patterns[:source].match source or source.nil? logger.warn "Source file '#{source}' not recognized" end # start generating conversion parameters params = [] # pandoc: I/O formats params << ['-f', metadata['input-format']] if metadata['input-format'] params << ['-t', metadata['output-format']] if metadata['output-format'] # pandoc: template and filter(s) params << ['--template', metadata['template']] if metadata['template'] && !options[:feed] [metadata['filter'] || metadata['filters']].flatten.each do |filter| params << ['--filter', filter] end if metadata['filter'] || metadata['filters'] # pandoc: bibliography file name if metadata['source-bibliography'] and File.exist?(File.join(source_dir, metadata['source-bibliography'])) params << ['--bibliography', File.join(source_dir, metadata['source-bibliography'])] end # pandoc: target (output) file name if metadata['target'] && !options[:preview] && !options[:feed] params << ['--output', File.join(source_dir, metadata['target'])] end # pandoc: extra metadata (affects underlying document) id = get_relative_name(source_dir, $CurPath) unless id.empty? params << ['-M', "id=#{id}"] logger.info "<#{id}>" else logger.info '*top-level*' end # pandoc: raw option(s) [metadata['raw-option'] || metadata['raw-options']].flatten.each do |opt| params << opt end if metadata['raw-option'] || metadata['raw-options'] # pandoc: extra parameters (provided as command-line args) params << options[:extra_params] if options[:extra_params] # pandoc: source file params << File.expand_path(source) unless source.nil? # pandoc: metadata file name if metadata['source-metadata'] and File.exist?(File.join(source_dir, metadata['source-metadata'])) params << File.join(source_dir, metadata['source-metadata']) end # pandoc: preloaded metadata files params << metadata[:files] if metadata[:files] logger.info "Generating: #{([options[:converter]] + params).flatten.join ' '}" return 0 if options[:dry] Open3.popen3(options[:converter], *params.flatten) do |stdin, stdout, stderr, wait_thr| out, err = stdout.read, stderr.read if wait_thr.value.success? logger.warn err unless err.empty? logger.info 'Done' if options[:preview] || options[:feed] file_id = get_relative_name(File.expand_path(source), $CurPath) $Cache[file_id] = { 'body' => out } if !options[:port].nil? logger.info('Preview at: ' + URI.escape("http://localhost:#{options[:port]}/#{file_id}")) end end else logger.error "Failed to generate from '#{source}'" logger.error err end return wait_thr.value.exitstatus end end end # Build the feed. (synchronous) # Return: exit status of the converter process. def build_feed(site_dir = '.', options = {}, logger = Logger.new(STDERR)) metadata = load_config_all(site_dir) # preload if metadata['canonical'].nil? logger.fatal "Metadata field 'canonical' not found. Can't build feed" raise "Metadata field 'canonical' not found. Can't build feed" elsif metadata['feed'].nil? logger.fatal "Metadata field 'feed' not found. Can't build feed" raise "Metadata field 'feed' not found. Can't build feed" elsif metadata['feed']['file'].nil? logger.fatal "Metadata field 'feed.file' not found. Can't build feed" raise "Metadata field 'feed.file' not found. Can't build feed" elsif metadata['feed-template'].nil? logger.fatal "Metadata field 'feed-template' not found. Can't build feed" raise "Metadata field 'feed-template' not found. Can't build feed" elsif metadata['feed-cache'].nil? logger.fatal "Metadata field 'feed-cache' not found. Can't build feed" raise "Metadata field 'feed-cache' not found. Can't build feed" end logger.info "*#{metadata['feed']['file']}*" feed = { 'canonical' => metadata['canonical'], 'feed' => metadata['feed'], 'entry' => [] } $Cache.each do |file_id, val| # use all cached pages m = YAML.load_file file_id id = get_relative_name(File.expand_path('..', file_id), $CurPath) val['id'] = id val['title'] = m['title'] if !m['title'].nil? val['author-name'] = m['author'] if !m['author'].nil? val['published'] = Time.parse(m['date'].to_s).strftime('%FT%T%:z') if !m['date'].nil? val['updated'] = Time.parse(m['date-updated'].to_s).strftime('%FT%T%:z') if !m['date-updated'].nil? if !m['category'].nil? val['category'] = m['category'] elsif !m['categories'].nil? val['category'] = m['categories'] end val['link'] = m['link'] if !m['link'].nil? # workaround: pandoc passes through backslashed notations in math formulae # use a place holder first val['body-holder'] = "\\$#{id}\\$" feed['entry'] << val if val['published'] && !File.exist?(File.join(id, '.archived')) # post without published date or with a '.archived' indicator is ignored! end feed['entry'].sort! { |x, y| y['published'] <=> x['published'] } if !feed['entry'].empty? feed['feed']['updated'] = feed['entry'][0]['published'] end # write to intermediate YAML file File.open(File.join(site_dir, metadata['feed-cache']), 'w') do |h| h.write feed.to_yaml h.write '---' end if !options[:dry] params = ['--template', metadata['feed-template'], '-t', 'html', '-o', metadata['feed']['file'], metadata['feed-cache']] logger.info "Generating: #{([options[:converter]] + params).flatten.join ' '}" return 0 if options[:dry] Open3.popen3(options[:converter], *params) do |stdin, stdout, stderr, wait_thr| out, err = stdout.read, stderr.read if wait_thr.value.success? # workaround: write entry body tmp = File.read(File.join(site_dir, metadata['feed']['file'])) tmp.gsub! /\$([^$]+)\$/ do |s| file_id = "#{s[1..-2]}/#{metadata['source']}" $Cache[file_id] ? $Cache[file_id]['body'] : s end File.open(File.join(site_dir, metadata['feed']['file']), 'w') do |h| h.write(tmp) end logger.warn err unless err.empty? logger.info 'Done' else logger.error "Failed to build feed" logger.error err end return wait_thr.value.exitstatus end end # main entry point if __FILE__ == $0 # get current path $CurPath = File.expand_path '.' # initialize cache $Cache = {} # set logging utility logger = Logger.new STDERR logger.formatter = proc do |severity, datetime, progname, msg| dt = datetime.strftime '%Y-%m-%d %H:%M:%S' case severity when 'FATAL' # red bold "\33[31;1m[#{dt}] #{severity} #{msg}\33[0m\n" when 'ERROR' # yellow bold "\33[33;1m[#{dt}] #{severity} #{msg}\33[0m\n" when 'WARN' # yellow "\33[33m[#{dt}] #{severity} #{msg}\33[0m\n" when 'INFO' # white "\33[37m[#{dt}] #{severity} #{msg}\33[0m\n" else "[#{dt}] #{severity} #{msg}\n" end end logger.level = Logger::INFO # default logging level # parse options options = { # default option values :converter => 'pandoc', :port => '8000', # nil if --no-server :watch => './', # nil if --no-watch :latency => 0.25, # pass to Listen :wait_for_delay => 0.10, # pass to Listen :reaction_time => 0, # FIXME: NOT IMPLEMENTED :use_changed => true, :recursive => false, :preview => false, :dry => false, :feed => false, :preload => true, :extra_params => [] # must be empty for now } OptionParser.new do |opts| opts.set_banner "Usage: pi [options] [sources]\n\n" opts.on('-C', '--converter [PROGRAM]', 'Set document converter (default: pandoc)') do |p| options[:converter] = p end opts.on('-P', '--port [PORT]', 'Set server port (default: 8000)') do |p| options[:port] = p end opts.on('-W', '--watch [PATH]', 'Set path to watch for changes (default: ./)') do |p| if File.directory? p options[:watch] = p else logger.error "Invalid watching path '#{p}'. Defaulted to ./" end end opts.on('--latency [SECONDS]', 'Set delay between checking for changes (default: 0.25)') do |s| options[:latency] = s.to_f end opts.on('--wait_for_delay [SECONDS]', 'Set delay between calls to the callback (default: 0.1)') do |s| options[:wait_for_delay] = s.to_f end # TODO #opts.on('-R', '--reaction-time [SECONDS]', # 'Set reaction time (default: 0)') do |s| # options[:reaction_time] = s.to_f #end opts.on('-D', '--disuse-changed', 'Do not use changed file to regenerate') do options[:use_changed] = false end opts.on('-r', '--recursive', 'Generate recursively') do options[:recursive] = true end opts.on('-p', '--preview', 'Preview by path') do options[:preview] = true end opts.on('--dry', 'Dry run') do options[:dry] = true end opts.on('-f', '--feed', 'Build feed') do options[:feed] = true end opts.on('-P', '--no-preload', 'Do not load configuration files (if any)') do options[:preload] = false end opts.on('--no-server', 'Do not start server') do options[:port] = nil end opts.on('--no-watch', 'Do not watch for changes') do options[:watch] = nil end opts.on('-v', '--[no-]verbose', 'Run verbosely') do |v| logger.level = v ? Logger::INFO : Logger::WARN end opts.on('-d', '--debug', 'Enable debug messages') do logger.level = Logger::DEBUG end opts.on('-V', '--version', 'Show program name and version') do puts opts.ver exit end end.parse! logger.debug 'options: ' + options.to_s # read sources / extra parameters sources = [] ARGV.each_index do |arg_no| source = ARGV[arg_no] if options[:extra_params].empty? # sanity check if source.start_with? '/' logger.fatal "Absolute path '#{source}' not allowed" raise "Absolute path '#{source}' not allowed" elsif File.exist? source sources << source elsif source.start_with? '-' options[:extra_params] << source else logger.fatal "Source file '#{source}' not found" raise "Source file '#{source}' not found" end else options[:extra_params] << source end end logger.debug 'sources: ' + sources.to_s logger.debug 'extra_params: ' + options[:extra_params].to_s # generate from sources sources.each do |source| make(source, init_metadata = {}, preload = options[:preload], options = options, logger = logger) end if options[:feed] # build feed build_feed('.', options = options, logger = logger) exit end if !options[:watch].nil? # start listener logger.info "Listening to: #{$Patterns[:source]}" listener = Listen.to(options[:watch], only: Regexp.union(#$Patterns[:config], #$Patterns[:metadata], $Patterns[:source], #$Patterns[:bibliography] ), latency: options[:latency], wait_for_delay: options[:wait_for_delay]) do |m, a, r| m.each do |path| source = get_relative_name(path, $CurPath) logger.info "File modified: #{source}" if options[:use_changed] # regenerate from source make(source, init_metadata = {}, preload = options[:preload], options = options, logger = logger) else make(nil, init_metadata = {}, preload = options[:preload], options = options, logger = logger) end end unless m.empty? a.each do |path| source = get_relative_name(path, $CurPath) logger.info "File added: #{source}" if options[:use_changed] # regenerate from source make(source, init_metadata = {}, preload = options[:preload], options = options, logger = logger) else make(nil, init_metadata = {}, preload = options[:preload], options = options, logger = logger) end end unless a.empty? r.each do |path| source = get_relative_name(path, $CurPath) #logger.info "File removed: #{source}" # TODO: remove generated files end unless r.empty? end logger.info "Watching: #{options[:watch]}" listener.start end if !options[:port].nil? # start preview server server = nil loop do begin if logger.level <= Logger::DEBUG server = WEBrick::HTTPServer.new( :Port => options[:port], :DocumentRoot => Dir::pwd ) else server = WEBrick::HTTPServer.new( :Port => options[:port], :DocumentRoot => Dir::pwd, :Logger => WEBrick::Log.new(File.open(File::NULL, 'w')), :AccessLog => [] ) end break rescue logger.warn "Port #{options[:port]} used; check out next port number" options[:port] = (options[:port].to_i + 1).to_s end end if options[:preview] server.mount_proc '/' do |request, response| id = get_relative_name( File.join($CurPath, URI.unescape(request.request_uri.path)), $CurPath) if File.exists? id if $Patterns[:source].match id if $Cache[id].nil? make(id, init_metadata = {}, preload = options[:preload], options = options, logger = logger) end # FIXME: what if still nil? response.status = 200 response['Content-Type'] = 'text/html; charset=UTF-8' response.body = $Cache[id]['body'] else # FIXME: resource files? end elsif id.empty? # show index (a list of cached pages) response.status = 200 response['Content-Type'] = 'text/html; charset=UTF-8' response.body += "Cached pages:\n" response.body += "<ul>\n" $Cache.each_key do |key| response.body += "<li><a href='#{key}'>#{key}</a></li>\n" end response.body += "</ul>\n" else response.status = 404 response['Content-Type'] = 'text/html; charset=UTF-8' response.body = 'The file or folder does not exist.' end end end # enter server loop logger.info "Server started: http://localhost:#{options[:port]}/" trap('INT') { server.shutdown } server.start end end
true
c35948e5462fd1344402791a2fd14258d38d57a8
Ruby
jdhunterae/sim-venture
/rb_v/tests.rb
UTF-8
681
3.140625
3
[ "MIT" ]
permissive
require './utils.rb' require './actions.rb' require './characters.rb' require './battles.rb' def test_character_stats people = [Fighter.new, Cleric.new, Mage.new, Thief.new] people.each { |person| puts person.get_sheet } end def test_monsters monsters = [Orc.new, Goblin.new] monsters.each { |monster| puts monster.get_sheet } end def test_battle person = Fighter.new monster = Goblin.new battle = Battle.new(person, monster, true) battle.run end def test_magic person = Mage.new monster = Goblin.new battle = Battle.new(person, monster, true) battle.run end def main # test_character_stats # test_monsters # test_battle test_magic end main
true
39c9a7316ea1bef10f3339f734bd04a304d63c9d
Ruby
aryaziai/simple-blackjack-cli-sf-web-091619
/lib/blackjack.rb
UTF-8
1,124
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def welcome puts "Welcome to the Blackjack Table" end def deal_card rand(1..11) end def display_card_total(total) total puts "Your cards add up to #{total}" end def prompt_user puts "Type 'h' to hit or 's' to stay" end def get_user_input get_user_input = gets.chomp end def end_game(total) puts "Sorry, you hit #{total}. Thanks for playing!" end def initial_round sum = 0 2.times do sum += deal_card end puts "Your cards add up to #{sum}" sum end def invalid_command puts "Please enter a valid command" end def hit?(prompt,input) prompt = prompt_user input = get_user_input end def hit?(number) prompt_user cardgame = get_user_input if cardgame == 's' return number elsif cardgame == 'h' number += deal_card else invalid_command hit?(number) end end def runner welcome anything = initial_round until anything > 21 do anything = hit?(anything) display_card_total(anything) end end_game(anything) end
true
73f82fa3d9f0ce91d5fb176854d30ae574fa7bca
Ruby
YukalatasKaslet/self
/Dummy_class.rb
UTF-8
585
4.09375
4
[]
no_license
puts "self es igual a: #{self}" class DummyClass def intance_method puts "Dentro de un método de instancia" puts "En este contexto self es igual a: #{self}" end def self.class_method puts "Dentro de un método de clase" puts "En este contexto self es igual a: #{self}" end end dummy_class = DummyClass.new() puts dummy_class.intance_method puts DummyClass.class_method #self nos sirve para saber en donde se está ubicando la acción #se puede estar ejecutando en el <main> #puede pertenecer a una instanciao a una clase.
true
a1c71a2e384d1de04c79e38e645a9af60f3b6171
Ruby
VasaStulo/Ruby
/Lab1_demo/lib/students.rb
UTF-8
625
2.75
3
[]
no_license
#frozen_string_literal: true require 'csv' # 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 class Students attr_reader :studentsList def initialize @studentsList = [] end def read_in_csv_data(file_name) CSV.foreach(file_name, headers:false) do |row| student = Student.new(row[0],row[1], row[2], row[3], row[4], row[5], row[6]) @studentsList.append(student) end end end
true
926a57c7039e4e1484c7950d1ff9dbbc98d97122
Ruby
aldelcy/IronHack-Class
/Week 1/Day 5/Chess/lib/pieces.rb
UTF-8
1,468
3.78125
4
[]
no_license
#PIECES require_relative "piece_info.rb" require_relative "move_value.rb" class Rook < Piece include Move def move?(x, y) move_value(x, y) if (@nw_x==0 && @nw_y>=0) || (@nw_x>=0 && @nw_y==0) true else false end end end #=============================== class King < Piece include Move def move?(x, y) move_value(x, y) if (@nw_x<=1 && @nw_y<=1) true else false end end end #=============================== class Knight < Piece include Move def move?(x, y) move_value(x, y) if (@nw_x==2 && @nw_y==1) || (@nw_x==1 && @nw_y==2) true else false end end end #=============================== class Bishop < Piece include Move def move?(x, y) move_value(x, y) if (@nw_x==@nw_y) true else false end end end #=============================== class Queen < Piece include Move def move?(x, y) move_value(x, y) if (@nw_x==@nw_y) || (@nw_x==0 && @nw_y>=0) || (@nw_x>=0 && @nw_y==0) true else false end end end #=============================== class BlackPawn < Piece include Move def move?(x, y) move_value(x, y) if @nw_x==0 && (y<=@y && @nw_y<=2) true else false end end end class WhitePawn < Piece include Move def move?(x, y) move_value(x, y) if @nw_x==0 && (y>=@y && @nw_y<=2) true else false end end end
true
093b2dc1b39a6a4e8762674b3d7467b6ee4049f6
Ruby
KaminKevCrew/Jumpstart_Lectures
/old_lectures/3-30-W1D3_lecture.rb
UTF-8
4,316
4.09375
4
[]
no_license
# Homework def average_of_three(num1, num2, num3) return (num1 + num2 + num3) / 3.0 end # p average_of_three(5, 6, 8) # a word is special if it starts with "c" OR has an even number of letters, but NOT both # Write a method special_word? that takes in a string and returns true if the word is special def special_word?(str) return (str[0].downcase == 'c') ^ (str.length.even?) end # puts special_word?("charisma") # false # puts special_word?("cat") # true # puts special_word?("even") # true # puts special_word?("c") # true # LOOPS # while (conditional express is true) # do something # end # while true # p "Infinite Loop" # end # # string[]: allows you to search for value # best_game = "Super Smash Bros Melee" # p best_game[0] # => "S" # p best_game[6..10] # => "Smash" # p best_game.length # => 22 # p best_game.include?("Q") # => false # p best_game.include?("Melee") # => true # p best_game.include?("Brawl") # => not in my house # using += # def count_to(number) # counter = 0 # while counter <= number # p counter # counter += 1 # end # end # count_to(165446876751321) # def count_down(number) # while number >= 0 # p number # number -= 1 # end # end # num = 100 # count_down(num) # string iteration loop # str = "jumpstart is fun!" # i = 0 # index variable # while i < str.length # p str[i] # i += 1 # end def count_a(str) count = 0 idx = 0 while idx < str.length if 'aA'.include?(str[idx]) # str[idx].downcase == 'a' char == 'a' || char == 'A' count += 1 end idx += 1 end return count end # p count_a("avatar aang") # 5 # p count_a("Avatar Aang") # 5 # p count_a("Abstemiously") # 1 # p count_a("Mississippi") # 0 # char == 'aA' #=> for this to be true, our char *must* be "aA" ## print all even numbers from 0 to the number inclusive, then return "finished!" def print_evens(number) evens = 0 while evens <= number p evens evens += 2 end return finish end # print_evens(10) # print_evens(39) # # takes a str and replaces all vowels with "*" def censor_words(str) censored = "" vowels = "aeiouAEIOU" idx = 0 while idx < str.length if vowels.include?(str[idx]) censored += '*' else censored += str[idx] end idx += 1 end return censored end # string = "This jumpstart is awesome!" # p censor_words("Hello AJ!") # "H*ll* *J!" # p censor_words("Abstemiously") # "*bst*m***sly" # p censor_words("Gravity Falls") # "Gr*v*ty F*lls" # p censor_words("Feck") # "F*ck" # p censor_words("Shut the Front Door!") # "Sh*t th* Fr*nt D**r!" # puts "\n\n" # p string # p censor_words(string) # "Sh*t th* Fr*nt D**r!" # p string # write a method is_prime? that takes in an number and returns true if # the number is prime, false otherwise def is_prime?(number) return false if number < 2 return true if number == 2 possible_fact = 2 while possible_fact < number if number % possible_fact == 0 return false end possible_fact += 1 end return true end # p is_prime?(2) # true # p is_prime?(3) # true # p is_prime?(97) # true # p is_prime?(1) # false # p is_prime?(4) # false # p is_prime?(9) # false # p is_prime?(121) # false # write a method all_primes_to that takes in a number and prints all primes # up to that number # HINT: use our is_prime helper method! def all_primes_to(number) test_num = 2 return nil if number < 2 while test_num <= number if is_prime?(test_num) p test_num end test_num += 1 end end p all_primes_to(23) #2,3,5,7,11,13,17,19 ### implement your own include version of string.include? # easy mode: you can assume search_term is one character # challenge mode: search for more than one character # my_include("chris","is") -> true # def my_include?(string, search_term) # end # p my_include?("avatar aang","a") # true # p my_include?("Fullmetal Alchemist","f") # false # p my_include?("avatar aang","tar") # true # p my_include?("teacher","cheat") # false # p my_include?("manslaughter","laughter") # true # string = "orangutan" # p string[4..6] #=> "gut" # string[i..???] #=> grab the right substring # search term has unlimited length => dynamically determine the required length of substring and the associated indices.
true
2000735af15c6334ccc0897fe4ca04f376ff17e0
Ruby
yezideteachers/projet
/spec/models/personne_spec.rb
UTF-8
649
2.546875
3
[]
no_license
require 'spec_helper' describe Personne do before do @personne = Personne.new(nom: "yezide") end describe "when name is not present" do before { @personne.nom = " " } it { should_not be_valid } end describe "when name is too long" do before { @personne.nom = "a" * 45 } it { should_not be_valid } end describe "when nom is already taken" do before do personne_with_same_nom = @personne.dup personne_with_same_nom.save end it { should_not be_valid } end # it "exige un nom" do # bad_guy = Personne.new(@attr.nom(:nom => "")) # bad_guy.should_not be_valid # end end
true