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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ab2b0c36cc8bf7f916532b2e95697e91c9c46530 | Ruby | abdulkalam7/kalam | /ex3.rb | UTF-8 | 419 | 3.484375 | 3 | [] | no_license | #ex3 badsic math opration calculation applies pemdas method
puts 'i\'ll count the totall numbers of chickens'
puts "hens = #{100-30*2}"
puts "roasters = #{100-25*3%4}"
puts "now i\'ii count the eggs"
puts 3+10.0-3/2*4%2
puts "is that true"
#finding true or false
puts 3+5>3-5
puts "what is 100-87. the answer is #{100-87}"
puts "its 5>=6 greater or equal #{5>=6}"
puts "is it greater? 5 > -2 #{5>-2}" | true |
5c4f9251865e849e8eadcd29fffec5bbdbe0ac2b | Ruby | RichardGregoryHamilton/Conversions | /spec/temperature_spec.rb | UTF-8 | 534 | 3 | 3 | [] | no_license | require 'spec_helper'
describe Temperature do
before :each do
@temperature = Temperature.new(56)
end
describe "#new" do
it "should create a new temperature object" do
expect(@temperature.instance_of?(Temperature)).to be(true)
end
end
describe "#to_farenheit" do
it "should convert to farenheit" do
expect(@temperature.to_farenheit).to eql(56)
end
end
describe "#to_celsisus" do
it "should convert to celsius" do
expect(@temperature.to_celsius).to eql(13)
end
end
end
| true |
a60d25e339652de27a3a877f8b4ab5404f93cec8 | Ruby | jastack/projects | /board.rb | UTF-8 | 1,430 | 3.71875 | 4 | [] | no_license | require_relative 'piece'
require_relative 'null_piece'
class Board
attr_reader :grid
def initialize
set_grid
end
def set_grid
end_rows = Array.new(2) { Array.new(8) { Piece.new } }
mid_rows = Array.new(4) { Array.new(8) { NullPiece.new } }
other_rows = Array.new(2) { Array.new(8) { Piece.new } }
@grid = end_rows + mid_rows + other_rows
end
def move_piece(start_pos, end_pos)
raise "not a valid move" unless valid_move?(start_pos, end_pos)
if self[start_pos].color != self[end_pos].color
self[end_pos] = self[start_pos]
self[start_pos] = NullPiece.new
else
self[start_pos], self[end_pos] = self[end_pos], self[start_pos]
end
end
def valid_move?(start_pos, end_pos)
!empty?(start_pos) &&
(empty?(end_pos) || different_colors?(start_pos, end_pos)) &&
in_bounds([start_pos, end_pos]).length == 2 &&
self[start_pos].valid_movement?(start_pos, end_pos)
end
def in_bounds(positions_array)
positions_array.select { |position| in_bounds?(position) }
end
def in_bounds?(pos)
row, col = pos
(0..7).include?(row) && (0..7).include?(col)
end
def different_colors?(pos1, pos2)
self[pos1].color != self[pos2].color
end
def empty?(pos)
self[pos].is_a?(NullPiece)
end
def [](pos)
row, col = pos
@grid[row][col]
end
def []=(pos,val)
row, col = pos
@grid[row][col] = val
end
end
| true |
32d5e9c65ffa2d4008bc724eba6989d57f324169 | Ruby | EARoa/IronYard-Day3 | /homework.rb | UTF-8 | 1,631 | 4.03125 | 4 | [] | no_license | # Just like yesterday's homework
# This time as much as possible do not look back at previous examples.
# Be sure to use git to add your homework changes to your repo on github.
# BONUS + Highly recommened, use comments to describe what is happening with each step
# PART 1
# 1. Make an array of your classmate's names
# Part homework... part Ice Breaker... part review... #winning
# PART 2
# 1. Create an array of the words in sentence
# 2. Find how many words have a length equal to 4
sentence = "Ruby is way better than JavaScript."
words = []
word = ""
sentence.chars.each do |c|
if c == " "
words << word
word = ""
else
word = word + c
end
end
words << word
p words
counter = 0
words.each do |word|
if word.length == 4
counter += 1
end
end
p counter
# PART 3
# 1. Create an array of movies with budgets less than 100
# 2. Create an array of movies that have Leonardo DiCaprio as a star
movies = []
movies << {
title: "Forest Gump",
budget: 55,
stars: ["Tom Hanks"]
}
movies << {
title: "Star Wars",
budget: 11,
stars: ["Mark Hamill", "Harrison Ford"]
}
movies << {
title: "Batman Begins",
budget: 150,
stars: ["Christian Bale", "Liam Neeson", "Michael Caine"]
}
movies << {
title: "Titanic",
budget: 200,
stars: ["Kate Winslet", "Leonardo DiCaprio"]
}
movies << {
title: "Inception",
budget: 160,
stars: ["Leonardo DiCaprio", "JGL"]
}
cheap_movie = []
def leo?(movies)
leo = false
movies[:stars].each do |actor|
if actor == "Leonardo DiCaprio"
leo = true
end
end
return leo
end
movies.each do |cmovie|
if cmovie[:budget] < 100
cheap_movie << cmovie[:title]
end
end
p cheap_movie
| true |
8fecd5f9f16f1521c408349453b7b8b84ebb615f | Ruby | jokale/pokemon-scraper-online-web-ft-120919 | /lib/pokemon.rb | UTF-8 | 628 | 3.5 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Pokemon
attr_accessor :id, :name, :type, :db
def initialize(id:1, name: "Pikachu", type: "electric", db: @db)
@id=id
@name=name
@type=type
@db =db
end
def self.save(name, type, db)
db.execute("INSERT INTO pokemon (name, type)
VALUES (?,?)", [name, type])
@id = db.execute("SELECT last_insert_rowid() FROM pokemon")[0][0]
end
def self.find(id, db)
pokemon = db.execute("SELECT * FROM pokemon WHERE id=?", id).flatten
id = pokemon[0]
name = pokemon[1]
type = pokemon[2]
db= db
Pokemon.new(id: id, name: name, type: type, db: db)
end
end | true |
36496d6dcaefde1285f1f7da09ddb9d83b8ce48f | Ruby | travisstyleup/travis-core | /lib/core_ext/module/async.rb | UTF-8 | 1,096 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'thread'
require 'singleton'
require 'delegate'
require 'monitor'
class Async
include Singleton
def initialize
@queue = Queue.new
Thread.new { loop { work } }
end
def work
block = @queue.pop
block.call if block
rescue Exception => e
puts e.message, e.backtrace
end
def run(&block)
@queue.push block
end
end
class Work < Delegator
include MonitorMixin
attr_reader :result
def initialize(&work)
super(work)
@work = work
@done, @lock = false, new_cond
end
def process
synchronize do
@result, @done = @work.call, true
@lock.signal
end
end
def __getobj__
synchronize do
@lock.wait_while { !@done }
end
@result
end
def __setobj__(work)
@work = work
end
end
Module.class.class_eval do
def async(*names)
names.each do |name|
method = instance_method(name)
define_method(name) do |*args, &block|
work = Work.new { method.bind(self).call(*args, &block) }
Async.instance.run { work.process }
work.result
end
end
end
end
| true |
9eaaedfdbcfbc44b278f5d17f69a8b9d1e93d0ec | Ruby | jordannadroj/cookbook | /lib/controller.rb | UTF-8 | 1,891 | 3.1875 | 3 | [] | no_license | # controller
# require the model
require_relative 'recipe'
# require the view
require_relative 'view'
require_relative 'parsing'
require 'nokogiri'
require 'open-uri'
require "pry-byebug"
class Controller
attr_accessor :cookbook
def initialize(cookbook)
@cookbook = cookbook
@view = View.new
end
def list
display_recipes
end
def create
name = @view.ask_for_recipe
description = @view.ask_for_description
rating = @view.ask_for_rating
prep_time = @view.ask_for_prep_time
new_recipe = Recipe.new(name: name, rating: rating, description: description, prep_time: prep_time)
@cookbook.add_recipe(new_recipe)
return list
end
def user_search
# puts "What ingredient would you like a recipe for?"
# ingredient = gets.chomp
ingredient = @view.ask_for_ingredient
@view.searching_for_ingredient(ingredient)
# make an HTTP request with ingredient
imported_recipes = ScrapeAllRecipesService.new(ingredient).call
# display the recipes in an indexed list
@view.display(imported_recipes)
# ask the user which recipe they want to import
selected_index = @view.select_import
# add to the cookbook
recipe = imported_recipes[selected_index]
@view.importing_message(recipe)
@cookbook.add_recipe(recipe)
return list
end
def scrape_url(recipe_url)
url = recipe_url
html_content = open(url).read
doc = Nokogiri::HTML(html_content)
doc.search('.recipe-meta-item-body').first.text.strip
end
def mark_as_done
display_recipes
index = @view.ask_user_for_index
recipe = @cookbook.mark_recipe_as_done(index)
return list
end
def destroy
display_recipes
recipe_index = @view.delete_recipe
@cookbook.remove_recipe(recipe_index)
display_recipes
end
def display_recipes
recipes = @cookbook.all
@view.display(recipes)
end
end
| true |
a97724918f6c5939ffd8f758f9e7825eb91ea560 | Ruby | vijendra/mars-rovers | /lib/rover.rb | UTF-8 | 685 | 3.359375 | 3 | [
"MIT"
] | permissive | class Rover
attr_accessor :position
def initialize(params, plateau)
@position = Position.new(params, plateau)
end
def process_instructions(instruction)
instruction.each_char do |command|
case command
when 'M' then move_forward
when 'L' then turn_left
when 'R' then turn_right
end
end
end
def turn_left
@position.turn_left
end
def turn_right
@position.turn_right
end
def move_forward
@position.move_forward
end
def current_position
@position.current_position
end
def x
@position.x
end
def y
@position.y
end
def orientation
@position.orientation
end
end
| true |
73bf7f34e7e16a9dab709d65fb3be6e0070fb924 | Ruby | yuichiro19/mahjong-score | /app/controllers/scores_controller.rb | UTF-8 | 3,389 | 2.546875 | 3 | [] | no_license | class ScoresController < ApplicationController
before_action :set_game
before_action :set_scores, only: [:index, :show]
before_action :authenticate_user!
def index
@score = Score.new
end
def create
point_calc
@score = Score.create(score_params)
if @score.save
redirect_to game_scores_path
else
render :index
end
end
def show
end
def destroy
score = Score.find(params[:id])
score.destroy
redirect_to game_scores_path
end
private
def set_game
@game = Game.find(params[:game_id])
end
def set_scores
@scores = @game.scores.includes(:game)
end
def score_params
params.require(:score).permit(:user_score, :guest1_score, :guest2_score, :guest3_score, :user_rank, :guest1_rank, :guest2_rank, :guest3_rank, :user_point, :guest1_point, :guest2_point, :guest3_point).merge(
user_id: current_user.id, game_id: params[:game_id]
)
end
def point_calc
if params[:score][:user_rank] == '1'
params[:score][:guest1_point] = player_point_calc(params[:score][:guest1_score], params[:score][:guest1_rank])
params[:score][:guest2_point] = player_point_calc(params[:score][:guest2_score], params[:score][:guest2_rank])
params[:score][:guest3_point] = player_point_calc(params[:score][:guest3_score], params[:score][:guest3_rank])
params[:score][:user_point] =
-(params[:score][:guest1_point] + params[:score][:guest2_point] + params[:score][:guest3_point])
elsif params[:score][:guest1_rank] == '1'
params[:score][:user_point] = player_point_calc(params[:score][:user_score], params[:score][:user_rank])
params[:score][:guest2_point] = player_point_calc(params[:score][:guest2_score], params[:score][:guest2_rank])
params[:score][:guest3_point] = player_point_calc(params[:score][:guest3_score], params[:score][:guest3_rank])
params[:score][:guest1_point] =
-(params[:score][:user_point] + params[:score][:guest2_point] + params[:score][:guest3_point])
elsif params[:score][:guest2_rank] == '1'
params[:score][:user_point] = player_point_calc(params[:score][:user_score], params[:score][:user_rank])
params[:score][:guest1_point] = player_point_calc(params[:score][:guest1_score], params[:score][:guest1_rank])
params[:score][:guest3_point] = player_point_calc(params[:score][:guest3_score], params[:score][:guest3_rank])
params[:score][:guest2_point] =
-(params[:score][:user_point] + params[:score][:guest1_point] + params[:score][:guest3_point])
else
params[:score][:user_point] = player_point_calc(params[:score][:user_score], params[:score][:user_rank])
params[:score][:guest1_point] = player_point_calc(params[:score][:guest1_score], params[:score][:guest1_rank])
params[:score][:guest2_point] = player_point_calc(params[:score][:guest2_score], params[:score][:guest2_rank])
params[:score][:guest3_point] =
-(params[:score][:user_point] + params[:score][:guest1_point] + params[:score][:guest2_point])
end
end
def player_point_calc(score, rank)
base_point = ((score.to_i - 100).round(-3) - @game.top_bonus.basic) / 1000
if rank == '2'
base_point + @game.rank_bonus.second_bonus
elsif rank == '3'
base_point + @game.rank_bonus.third_bonus
else
base_point + @game.rank_bonus.forth_bonus
end
end
end
| true |
20b1fafd1b6304b6a6dcf1411d94e9aaa53c4447 | Ruby | karen1130/CalculatorChallenge- | /CalcProject.rb | UTF-8 | 529 | 4.21875 | 4 | [] | no_license |
puts "What does x equal?"
x = gets.strip.to_f
puts "What does y equal?"
y = gets.strip.to_f
puts "What is your equation? Choose multiply, add, subtract, divide, exponent."
equation = gets.strip
if equation == "multiply"
puts "Your answer is #{x * y}"
elsif equation == "add"
puts "Your answer is #{x + y}"
elsif equation == "subtract"
puts "Your answer is #{x - y}"
elsif equation == "divide"
puts "Your answer is #{x / y}"
elsif equation == "exponent"
puts "Your answer is #{x ** y}"
end
| true |
e2bc44722d687e8254fdc48bb1e92c809e2bbb01 | Ruby | coyled/hdfshealth | /lib/hdfshealth/plugins/load_nn_jmx.rb | UTF-8 | 1,703 | 2.546875 | 3 | [
"MIT"
] | permissive | #
# load namenode /jmx output for use by other plugins
#
class LoadNNJMX < HDFSHealth::Plugin
require 'uri'
require 'net/http'
require 'json'
@jmx = {}
def self.jmx(namenode)
unless @jmx[namenode]
self.fetch_jmx(namenode)
end
@jmx[namenode]
end
def self.fetch_jmx(namenode)
uri = URI.parse(namenode)
if uri.scheme == 'file'
begin
jmx = File.read(uri.path)
rescue Errno::ENOENT
print 'file not found. exiting...'
exit(1)
end
elsif uri.scheme == 'http' or uri.scheme == 'https'
begin
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 5
if uri.scheme == 'https'
http.use_ssl = true
end
response = http.request(Net::HTTP::Get.new(uri.request_uri))
jmx = response.body
rescue Net::OpenTimeout
print 'timeout trying to retrieve JMX data from namenode.' \
'did you use the correct hostname/port? exiting...'
exit(1)
end
end
stats = JSON.parse(jmx)
stats['beans'].each do |data|
self.parse_jmx(namenode, data)
end
end
def self.parse_jmx(namenode, data)
@jmx[namenode] ||= {}
if data['name'] == 'Hadoop:service=NameNode,name=FSNamesystem'
@jmx[namenode]['FSNamesystem'] ||= data
elsif data['name'] == 'Hadoop:service=NameNode,name=NameNodeInfo'
@jmx[namenode]['NameNodeInfo'] ||= data
end
end
end
| true |
4a4c158eecd04084541e18ea3c71962a894ede28 | Ruby | Arielle919/linked_list_cohort3 | /lib/linked_list.rb | UTF-8 | 1,450 | 3.40625 | 3 | [] | no_license | class LinkedList
attr_accessor :payload, :head_item
def initialize(*payload)
@last_node = nil
@count = 0
payload.each do |item|
add_item(item)
end
end
def add_item payload
if @head_node.nil?
@head_node = LinkedListItem.new(payload)
@count += 1
@last_node = @head_node
else
last_node = @head_node
while last_node.last? == false
last_node = last_node.next_list_item
end
last_node.next_list_item = LinkedListItem.new(payload)
@count +=1
@last_node = @last_node.next_list_item
end
end
def get(index)
if index < 0
raise IndexError
else
initial_node = @head_node
index.times do #this is a ruby loop
if initial_node == nil
raise IndexError
else
initial_node = initial_node.next_list_item
end
end
initial_node.payload
end
end
def size
return @count
end
def last
if @last_node == nil
nil
else
@last_node.payload
end
end
def to_s
if @head_node == nil
'| |'
else
@node_array = @head_node.payload
head_node = @head_node
while head_node.last? == false
@node_array += ", #{head_node.next_list_item.payload}"
head_node = head_node.next_list_item
end
'| ' + @node_array + ' |'
end
end
def []
node = "grille"
end
def [](index)
node = "grille"
end
end | true |
a4c31f14810a3cc3b88db2ec721a82f39543e30d | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/hamming/fc2dba92c923475e8c7ff72fd922ce53.rb | UTF-8 | 536 | 3.390625 | 3 | [] | no_license | class Hamming
def self.compute(dna_strand_1, dna_strand_2)
dna_strand_1_array = dna_strand_1.split(//)
dna_strand_2_array = dna_strand_2.split(//)
length_shortest_strand = dna_strand_1.length
length_shortest_strand = dna_strand_2.length if dna_strand_2.length < dna_strand_1.length
i=0
hamming_distance = 0
while i < length_shortest_strand
if dna_strand_1_array[i] != dna_strand_2_array[i]
hamming_distance = hamming_distance+1
end
i+=1
end
hamming_distance
end
end
| true |
143a947537a376a9b53337bdb793b9f1d543d044 | Ruby | Zequez/mapa-de-transporte | /lib/my_encryptor.rb | UTF-8 | 343 | 2.875 | 3 | [
"MIT"
] | permissive | require 'base64'
class MyEncryptor
def self.encode(data)
Base64.encode64(data).strip.gsub(/\n|=/, "").reverse
end
def self.decode(data)
Base64.decode64(data.reverse + ("=" * (data.size % 4)))
end
def self.domain_validator(domain)
sum = 0
domain.each_codepoint {|l|sum += l*l}
sum.to_s
end
end | true |
d91dd578c4006517d2988d554104061bb0b9615d | Ruby | nskillen/aoc2018 | /mkday.rb | UTF-8 | 415 | 3.078125 | 3 | [] | no_license | require 'fileutils'
day = lambda do |d|
<<~EOF
require_relative 'day'
require 'io/console'
class #{d.upcase} < Day
def wait
puts "Press any key to continue..."
STDIN.getch
end
def part_one
end
def part_two
end
end
EOF
end
d = "d#{ARGV[0]}"
d = d[1..-1] if d.start_with?("dd")
FileUtils.touch("input/#{d}.txt")
File.open("#{d}.rb", "w") do |f|
f.write day.call(d)
end
| true |
b3143ff764e82ad3dcb965881879ceae80a8a29c | Ruby | Hamzaoutdoors/School_Library_Ruby | /library/rentals/main.rb | UTF-8 | 1,406 | 3.734375 | 4 | [] | no_license | require './library/rentals/rental'
class RentalIntializer
def initialize
@rentals = []
end
def create_rental(books, people)
if people.empty? && books.empty?
puts 'Your Library is empty add books and people'
return
end
puts 'Select a book from the following list by number'
books.each_with_index do |book, i|
print "#{i}) Title: #{book.title}, Author: #{book.author}\n"
end
book_index = gets.chomp.to_i
book = books[book_index]
puts 'Select a person from the following list by number (not ID)'
people.each_with_index do |person, i|
print "#{i}) [#{person.class}] Name: #{person.name.capitalize}, ID: #{person.id}, Age: #{person.age}\n"
end
person_index = gets.chomp.to_i
person = people[person_index]
print "\nDate: "
date = gets.chomp
save_rental(date, person, book)
end
def save_rental(date, person, book)
rental = Rental.new(date, person, book)
@rentals << rental
puts "Rental created successfully\n"
end
def list_all_rental
print 'ID of person: '
id = gets.chomp.to_i
puts 'Rentals: '
rentals = @rentals.select { |rental| rental.person.id == id }
if rentals.empty?
puts 'No rentals found'
return
end
rentals.each do |rental|
print "Date: #{rental.date}, Book \'#{rental.book.title}\' by #{rental.book.author}\n"
end
end
end
| true |
8e9ecfbf23b71580dfe68bbb2acab46ca55ec932 | Ruby | ggerdsen/Web_Scraper_Ruby | /lib/scraper.rb | UTF-8 | 1,017 | 2.859375 | 3 | [
"MIT"
] | permissive | require_relative 'output.rb'
class Scraper
include Output
attr_accessor :page
def initialize(page)
@page = page.read_html
end
def jobs_list
jobs = []
job_offers = @page.css('div.jobsearch-SerpJobCard')
job_offers.each do |entry|
job = job(entry)
jobs << job
end
jobs
end
private
def job(entry)
{
title: string_filter(entry.css('.title').text),
location: string_filter(entry.css('span.location').text),
date_publication: string_filter(entry.css('span.date').text),
company: string_filter(entry.css('.company').text),
summary: string_filter(entry.css('div.summary').text),
url: "https://www.indeed.com#{entry.css('a.jobtitle')[0].attributes['href'].value}"
}
end
def string_filter(my_string)
if my_string.empty?
'Data not Availible'
else
output = my_string.gsub(/[\n\r\t]/, '')
output = output.delete_prefix(' ')
output = output.delete_suffix('new')
output
end
end
end
| true |
b40225aa2f20603980f85daa53e81d323801bd98 | Ruby | vendetta546/codewars | /Ruby/6KYU/StringRotate.rb | UTF-8 | 999 | 4 | 4 | [] | no_license | =begin
Write a function that receives two strings and returns n, where n is equal to
the number of characters we should shift the first string forward to match the
second.
For instance, take the strings "fatigue" and "tiguefa". In this case, the first
string has been rotated 5 characters forward to produce the second string, so 5
would be returned.
If the second string isn't a valid rotation of the first string, the method
returns -1.
Examples:
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
=end
# My Solution
def shifted_diff(first, second)
(0..first.length-1).each do |x|
return x if first == second
first = first.split("").rotate(-1).join
end
return -1
end
# Better Solution
def shifted_diff(first, second)
(0..second.size).each {|n|return n if first == second.chars.rotate(n).join}
-1
end
# Another Solution
def shifted_diff f, s
f.size==s.size&&(s*2).index(f)||-1
end
| true |
3662b5a63b90f1b0385a9a7013abf1ec0a8aa89f | Ruby | WojciechKo/ruby-playground | /spec/instance_method_spec.rb | UTF-8 | 981 | 2.53125 | 3 | [] | no_license | RSpec.describe 'Module#instance_method' do
let(:arrays) { [['a', 'b'], ['c'], ['d', 'e']] }
let(:hashs) { [{ 'a' => 1 }, { 'b' => 2, 'c' => 3 }, { 'd' => 4, 'e' => 5 }] }
specify do
expect(arrays[0].zip(*arrays[1..]))
.to match_array([['a', 'c', 'd'], ['b', nil, 'e']])
expect(Array.instance_method(:zip).bind_call(*arrays))
.to match_array([['a', 'c', 'd'], ['b', nil, 'e']])
end
specify do
expect(arrays[0].product(*arrays[1..]))
.to match_array([['a', 'c', 'd'], ['a', 'c', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e']])
expect(Array.instance_method(:product).bind_call(*arrays))
.to match_array([['a', 'c', 'd'], ['a', 'c', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e']])
end
specify do
expect(hashs[0].merge(*hashs[1..]))
.to eq({ 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 })
expect(Hash.instance_method(:merge).bind_call(*hashs))
.to eq({ 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 })
end
end
| true |
c534d83583721f392608d6036c191e13e2fa929d | Ruby | honorwoolong/launch_school | /RB101/Lesson_6/tictactoe_bonus_adv.rb | UTF-8 | 4,668 | 3.90625 | 4 | [] | no_license | require 'pry'
require 'pry-byebug'
# ask if player wants to go first or not
# 1 display the board
# 2 player place the piece
# 3 computer place the piece
# if player has 2 squares marked, computer must pick the 3rd square
# else put square randomly
# 4 continue until someone won 5 games
# display score
# restart the game
# the one won the game adding one score
# stop until someone won 5 times
# 5 if game is tie, go back to #2
# 6 play again? if yes, go back to #1
# 7 If no, goodbye to the game
INITIAL_MARKER = ' '.freeze
PLAYER_MARKER = 'O'.freeze
COMPUTER_MARKER = 'X'.freeze
WIN_LINE = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] +
[[1, 5, 9], [3, 5, 7]].freeze
def prompt(msg)
puts "=> #{msg}"
end
def joinor(arr, mid = ', ', last = 'or')
case arr.size
when 0 then ''
when 1 then arr.first
when 2 then arr.join(" #{last} ")
else
arr.join(mid).insert(-2, last + ' ')
end
end
def initial_board
board = {}
(1..9).each { |num| board[num] = INITIAL_MARKER }
board
end
# rubocop:disable Metrics/MethodLength, Metric/AbcSize
def update_board(brd, p_point, c_point)
system 'clear'
prompt "player is #{PLAYER_MARKER}, computer is #{COMPUTER_MARKER}"
puts ' | |'
puts " #{brd[1]} | #{brd[2]} | #{brd[3]}"
puts ' | |'
puts '-----+-----+-----'
puts ' | |'
puts " #{brd[4]} | #{brd[5]} | #{brd[6]}"
puts ' | |'
puts '-----+-----+-----'
puts ' | |'
puts " #{brd[7]} | #{brd[8]} | #{brd[9]}"
puts ' | |'
prompt "Player : Computer = #{p_point} : #{c_point}"
end
# rubocop:enable Metrics/MethodLength
def left_square(brd)
brd.keys.select { |num| brd[num] == INITIAL_MARKER }
end
def player_place_piece(brd)
square = ''
loop do
prompt "Choose a position to place a piece: #{joinor(left_square(brd))}"
square = gets.chomp.to_i
break if left_square(brd).include?(square)
prompt 'Please choose a valid number!'
end
brd[square] = PLAYER_MARKER
end
def find_risk_square(line, brd, marker)
if brd.values_at(*line).count(marker) == 2
brd.select { |k, v| line.include?(k) && v == INITIAL_MARKER }.keys.first
end
end
def computer_place_piece(brd)
square = nil
# offensive
WIN_LINE.each do |line|
square = find_risk_square(line, brd, COMPUTER_MARKER)
break if square
end
# defensive
unless square
WIN_LINE.each do |line|
square = find_risk_square(line, brd, PLAYER_MARKER)
break if square
end
end
# pick #5 square if still available
square = 5 if !square && left_square(brd).include?(5)
# pick randomly
square = left_square(brd).sample unless square
brd[square] = COMPUTER_MARKER
end
def winner_lines(brd)
WIN_LINE.each do |line|
return 'Player' if brd.values_at(*line).count(PLAYER_MARKER) == 3
return 'Computer' if brd.values_at(*line).count(COMPUTER_MARKER) == 3
end
nil
end
def someone_won?(brd)
winner_lines(brd).class == String
end
def alternate_player(current_player)
case current_player
when 'Player' then 'Computer'
when 'Computer' then 'Player'
end
end
def place_piece!(brd, current_player)
case current_player
when 'Player' then player_place_piece(brd)
when 'Computer' then computer_place_piece(brd)
end
end
answer = ''
board = {}
player_score = 0
computer_score = 0
current_player = ''
loop do
prompt 'Would you want to play first?(y/n)'
answer = gets.chomp
if answer.downcase.start_with?('y')
current_player = 'Player'
else
current_player = 'Computer'
end
loop do
board = initial_board
update_board(board, player_score, computer_score)
loop do
if left_square(board).empty?
update_board(board, player_score, computer_score)
prompt "It's a tie! Press enter to continue!"
answer = gets.chomp
board = initial_board if answer.empty?
else
update_board(board, player_score, computer_score)
place_piece!(board, current_player)
current_player = alternate_player(current_player)
break if someone_won?(board)
end
end
player_score += 1 if winner_lines(board) == 'Player'
computer_score += 1 if winner_lines(board) == 'Computer'
update_board(board, player_score, computer_score)
break if player_score >= 5 || computer_score >= 5
end
prompt 'Player won the game!!' if player_score == 5
prompt 'Computer won the game!!' if computer_score == 5
prompt 'Do you want to play again?(y/n)'
answer = gets.chomp
break unless answer.downcase.start_with?('y')
player_score = 0
computer_score = 0
end
prompt 'Thank you for playing the game!! Goodbye!'
| true |
3870e3fdb5dd0834dba3c0efdc88c9a81310c6db | Ruby | serg-kovalev/url_shortener | /config.ru | UTF-8 | 531 | 2.5625 | 3 | [] | no_license | require 'rack'
require_relative 'url_shortener.rb'
class Application
def self.call(env)
req = Rack::Request.new(env)
res = Rack::Response.new
if req.path_info.match /\/get_short_url\/.+/
long_url = req.path_info.sub('/get_short_url/', '')
short_url = UrlShortener.new.get_short_url(long_url)
res['Content-Type'] = 'application/json'
res['Access-Control-Allow-Origin'] = '*'
res.write({long_url: long_url, short_url: short_url}.to_json)
end
res.finish
end
end
run Application
| true |
27e4eddeddff0960ab0eae2ba99deb61d6a10075 | Ruby | TimCummings/launch_school | /101-programming_foundations/ruby_basics/variable_scope.rb | UTF-8 | 2,556 | 4.21875 | 4 | [] | no_license | # variable_scope.rb
# What's My Value? (Part 1)
7
# Once the my_value method is exited, a remains 7 since it was modified only in the scope of the method, my_value; also, += does not mutate the caller for integers.
# What's My Value? (Part 2)
7
# The a outside the my_value method and the a inside the my_value method are different variables, even though they share the same name. += still does not mutate the caller, so the variable a outside the my_value method retains its value of 7.
# What's My Value? (Part 3)
7
# The variable a outside the scope of the my_value method is still not being mutated. The a = b inside the my_value method is creating a new, different variable named a within the scope of the my_value method; the a variable outside the my_value method is still not accessible within the method, and the = method also does not mutate the caller.
# What's My Value? (Part 4)
"Xy-zy"
# The []= method for strings mutates the caller so the string "Xyzzy" is modified.
# What's My Value? (Part 5)
"Xyzzy"
# The = method inside my_value does not mutate the caller; instead, the variable b is assigned to reference a different string: "yzzyX". Once outside my_value, the variable a remains unchanged and so does the string it references: "Xyzzy".
# What's My Value? (Part 6)
# Variable scope error: no such variable as a within the my_value method.
# The variable, a, is outside the scope of the my_value method. Unlike previous exercises, where a new variable named a was being created in the my_value method, this exercise tries to reference a variable named a within my_value when one does not yet exist.
# What's My Value? (Part 7)
3
# The variable a is modified within the do block to reference a new integer; the final one is 3.
# What's My Value? (Part 8)
# variable scope error: the variable a is defined only inside the do block so trying to puts a outside the block results in an undefined variable error.
# What's My Value? (Part 9)
7
# The do block defines its own variable a that holds each successive element from array. The += 1 is applied to the new a within the do block; once the do block exits, the original variable a remains unchanged.
# What's My Value? (Part 10)
# Variable scope error: undefined variable. This exercise is back to using a method instead of a block. There is no a defined within the my_value method so the line a += b generates an error.
# *** It does generate an error, but not a variable scope error; this generates an undefined method error: no method '+' for nil:NilClass
| true |
434f65d97ab32cda1fa6c82c648d73d25cb3c58e | Ruby | minling/ruby-oo-assessment-web-0615-public | /lib/array_list.rb | UTF-8 | 517 | 4.46875 | 4 | [] | no_license | # Create a method on array called `list` that iterates over the array it is
# called on and appends a number, a period, and a space to each element.
# e.g ["ich", "ni", "san"].make_list #=> ["1. ich", "2. ni", "3. san"]
class Array
# def list
# @array
# end
def make_list
self.map.with_index do |item, index|
"#{index+1}. " + item
end
end
end
# array = [1, 2, 3]
# array.make_list
# second_array = Array.new
# second_array = [1, 2, 3, 5, 6]
# second_array.make_list
# foo.make_list | true |
ee51570258bc2b7bfecb617c8316aa07de837b75 | Ruby | doryberthold1987/rollavg | /rollavg | UTF-8 | 8,133 | 3.3125 | 3 | [] | no_license | #!/usr/bin/env ruby
### rollavg --- Utility for calculating a simple rolling average.
## Copyright 2006 by Dave Pearson <davep@davep.org>
## $Revision: 1.8 $
##
## rollavg is free software distributed under the terms of the GNU General
## Public Licence, version 2. For details see the file COPYING.
############################################################################
# Add a rounding method to the Float class.
class Float
def round_to( n )
( self * ( 10 ** n ) ).round.to_f / ( 10 ** n )
end
end
############################################################################
# Class for tracking and calculating a rolling average (mean).
class RollingAverage
# Constructor
def initialize( window_size )
# Remember the window size.
@window_size = window_size
# Initialise the array.
@window = Array.new()
end
# Add a value.
def add( n )
# Add the value to the end of the window.
@window << n
# If the window is longer than the required length...
if @window.length > @window_size
# ...remove the oldest item.
@window.delete_at( 0 )
end
end
# Get the average.
def average
if @window.length == 0
0
else
( @window.inject( 0 ) {|x,y| x + y } ) / @window.length
end
end
def narrow
if @window.length > 0
@window.delete_at( 0 )
end
end
end
############################################################################
# Class for tracking and calculating a rolling average (mode).
class RollingMode < RollingAverage
# Get the average (mode).
def average
if @window.length.zero?
0
else
counts = {}
@window.each() do |n|
if counts.has_key?( n )
counts[ n ] = counts[ n ] + 1
else
counts[ n ] = 1
end
end
# TODO. More checking. No clear winner?
( counts.sort() {|a,b| b[ 1 ] <=> a[ 1 ] } )[ 0 ][ 0 ]
end
end
end
############################################################################
# Class for tracking and calculating a rolling average compass (mean).
class RollingCompass
# Constructor
def initialize( window_size )
@x = RollingAverage.new( window_size )
@y = RollingAverage.new( window_size )
end
# Add a value.
def add( n )
@x.add( Math.sin( ( n / 360.0 ) * ( Math::PI * 2 ) ) )
@y.add( Math.cos( ( n / 360.0 ) * ( Math::PI * 2 ) ) )
end
# Get the average.
def average
res = ( Math.atan2( @x.average(), @y.average() ) * ( 180 / Math::PI ) ).round_to( 2 )
if res < 0 then res += 360 end
if res == 360 then res = 0 end
res
end
def narrow
@x.narrow()
@y.narrow()
end
end
############################################################################
# Main utility code.
# We're going to use long options.
require "getoptlong"
# Set the default parameters.
$params = {
:delimeter => " ",
:field => 1,
:help => false,
:licence => false,
:replace => false,
:type => "mean",
:windowsize => 10,
:zerotest => false,
:zerofield => 1
}
# Print the help screen.
def printHelp
print "rollavg v#{/(\d+\.\d+)/.match( '$Revision: 1.8 $' )[ 1 ]}
Copyright 2006 by Dave Pearson <davep@davep.org>
http://www.davep.org/
Supported command line options:
-d --delimeter <text> Specify the field delimeter.
(default is a space).
-f --field <field> Specify which field to average.
(default is 1).
-r --replace Do a replace of the chosen field with the average
when printing output. Default is to only print the
rolling average.
-t --type <type> Type of average. Either `mean', `mode' or
'compass'.
-w --windowsize <size> Specify the size of the window.
(default is 10).
--zerofield <field> Specify which field should be used for the zero
test.
--zerotest Don't use a value in the average calculation
if the field specified by --zerofield is zero.
-L --licence Display the licence for this program.
-h --help Display this help.
"
end
# Print the licence.
def printLicence
print "rollavg - Utility for calculating a simple rolling average.
Copyright (C) 2006 Dave Pearson <davep@davep.org>
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 675 Mass
Ave, Cambridge, MA 02139, USA.
"
end
# Get the arguments from the command line.
begin
GetoptLong.new().set_options(
[ "--delimeter", "-d", GetoptLong::REQUIRED_ARGUMENT ],
[ "--field", "-f", GetoptLong::REQUIRED_ARGUMENT ],
[ "--help", "-h", GetoptLong::NO_ARGUMENT ],
[ "--licence", "-L", GetoptLong::NO_ARGUMENT ],
[ "--replace", "-r", GetoptLong::NO_ARGUMENT ],
[ "--type", "-t", GetoptLong::REQUIRED_ARGUMENT ],
[ "--windowsize", "-w", GetoptLong::REQUIRED_ARGUMENT ],
[ "--zerofield", GetoptLong::REQUIRED_ARGUMENT ],
[ "--zerotest", GetoptLong::NO_ARGUMENT ]
).each {|name, value| $params[ name.gsub( /^--/, "" ).intern ] = value }
rescue GetoptLong::Error
printHelp()
exit 1
end
# The need for help overrides everything else
if $params[ :help ]
printHelp()
elsif $params[ :licence ]
# As does the need for the legal mumbojumbo
printLicence()
else
# Ensure the numeric parameters are numeric.
$params[ :field ] = $params[ :field ].to_i
$params[ :windowsize ] = $params[ :windowsize ].to_i
$params[ :zerofield ] = $params[ :zerofield ].to_i
# Create the average object.
if $params[ :type ] == "mode"
avg = RollingMode.new( $params[ :windowsize ] )
elsif $params[ :type ] == "compass"
avg = RollingCompass.new( $params[ :windowsize ] )
else
avg = RollingAverage.new( $params[ :windowsize ] )
end
# For each file given on the command line (or from stdin if no files were
# given)...
( ARGV.length == 0 ? ( "-" ) : ARGV ).each do |file|
# Process the file. Note that "-" means process stdin.
( file == "-" ? $stdin : File.open( file ) ).each do |line|
# Split the line into fields.
fields = line.chomp.split( $params[ :delimeter ] )
# Does the field we're after exist?
if fields.length >= $params[ :field ]
# Should we add it to the average?
if !$params[ :zerotest ] or ( $params[ :zerotest ] and fields[ $params[ :zerofield ] - 1 ].to_f > 0 )
# Add it to the average object.
avg.add( fields[ $params[ :field ] - 1 ].to_f )
else
# Failed the zero test, narrow the size of the window
# instead.
avg.narrow()
end
end
# If we're doing replaced output
if $params[ :replace ]
# Replace the chosen field with the average.
fields[ $params[ :field ] - 1 ] = avg.average()
# Emit the line.
print "#{fields.join( $params[ :delimeter ] )}\n"
else
# Simply print the rolling average.
print "#{avg.average()}\n"
end
end
end
end
# All's well that ends well.
exit 0
### rollavg ends here
| true |
1f151e25c9868b3e67b22e9802de808725cbb1e1 | Ruby | scottefein/youve_got_mail | /youve_got_mail.rb | UTF-8 | 1,554 | 2.765625 | 3 | [] | no_license | require 'sinatra'
require 'uri'
require 'twilio-ruby'
require 'puma'
class YouveGotMail < Sinatra::Base
configure do
set :notify_numbers, ENV['NOTIFY_NUMBERS'].split(',')
set :twilio_number, ENV['TWILIO_NUMBER']
set :twilio_sid, ENV['TWILIO_SID']
set :twilio_token, ENV['TWILIO_TOKEN']
end
def twilio_auth
account_sid = settings.twilio_sid
auth_token = settings.twilio_token
client = Twilio::REST::Client.new account_sid, auth_token
end
def call_with_twilio(number, subject)
client = twilio_auth
url_subject = URI.escape(subject)
client.account.calls.create(
:from => "+#{settings.twilio_number}", # From your Twilio number
:to => "+#{number}", # To any number
# Fetch instructions from this URL when the call connects
:url => "http://#{request.host}/twilio_speak?subject=#{url_subject}"
)
end
def send_sms_with_twilio(number, subject)
client = twilio_auth
client.account.sms.messages.create(
:from => "+#{settings.twilio_number}",
:to => "+#{number}",
:body => subject
)
end
def notify(subject)
login_body = login
settings.notify_numbers.each do |number|
send_sms_with_twilio(number, subject)
call_with_twilio(number, subject)
end
end
post '/new_email_mail' do
mail = params
email_subject= mail['subject']
notify("You've Got an Email. Subject Line: #{email_subject}")
end
get '/test' do
notify("Test Subject")
"CALLING"
end
post '/twilio_speak' do
Twilio::TwiML::Response.new do |r|
r.Say params[:subject]
end.text
end
end
| true |
c02f0824f93978fd67203bb3057aad292ca5c3fc | Ruby | cyberkov/puppetdb-dokuwiki | /gendoc.rb | UTF-8 | 2,355 | 2.609375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'net/http'
require 'uri'
require 'pp'
require 'erb'
require 'pry'
class Wikipage
attr_accessor :error
include ERB::Util
def initialize(options = {})
unless options["error"]
@vars = {}
@error = false
options["facts"].each do |key,value|
@vars[key] = value
end
@name = options["name"]
@template = options[:template]
@overwrite = options[:overwrite]
else
@error = options["error"]
end
end
def render(template = @template)
ERB.new(File.read(template), nil, '-').result(binding)
end
def save(file)
unless File.exist?(file) and @overwrite == false
File.open(file, "w") do |f|
f.write(render)
end
else
puts "Refusing to write #{file}"
end
end
def show
puts render
end
def lookupvar(var)
return @vars[var]
end
def scope
self
end
def function_template(file)
file.each do |x|
return render(x)
end
end
def method_missing (method_name)
if @vars[method_name.to_s]
return @vars[method_name.to_s]
else
puts "#{method_name} not implemented"
raise NoMethodError
end
end
def to_hash
@vars
end
end
def ask_db(path)
puppetdb = "http://puppetdb.example.com:8080"
uri = URI.parse("#{puppetdb}/v1/#{path}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
params = { :query => '["=", ["node", "active"], true]' }
request.set_form_data(params)
request.initialize_http_header({"Accept" => "application/json"})
response = http.request(request)
return JSON.parse(response.body)
end
nodelist = ask_db("nodes")
#nodelist = [ "avl2101p.it.internal" ]
@docpath = "/appl/webapps/hostdocumentation/data/gitrepo/pages/server"
@factpath = "/appl/webapps/hostdocumentation/data/gitrepo/pages/facts"
nodelist.each do |node|
facts = ask_db("facts/#{node}")
docpage = Wikipage.new(facts.merge({ :template => 'template/host.txt.erb', :overwrite => false}) )
factpage = Wikipage.new(facts.merge({ :template => 'template/facts.txt.erb', :overwrite => true}) )
unless factpage.error
factpage.save("#{@factpath}/#{factpage.hostname}.txt")
docpage.save("#{@docpath}/#{factpage.hostname}.txt")
else
puts factpage.error
end
end
| true |
724dd1a19ba109d55c8464feca709b73abec5d12 | Ruby | eminisrafil/ShoutRoulette-Rails-Backend | /app/models/room.rb | UTF-8 | 2,972 | 2.5625 | 3 | [] | no_license | # == Schema Information
#
# Table name: rooms
#
# id :integer not null, primary key
# session_id :string(255)
# topic_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# agree :boolean
# disagree :boolean
#
class Room < ActiveRecord::Base
belongs_to :topic
has_many :observers
attr_accessible :session_id, :agree, :disagree, :closed, :short_session_id
def self.create_or_join(topic, params)
if params[:position] == 'observe'
selected_room = Room.find_observable_room(topic)
else
# find a room with an open seat for your position
throw 'dont hack me bro' unless params[:position ] == 'agree' or params[:position] == 'disagree'
#No one likes paying for Servers - Delete old records quickly not to go over 10,000 rows again///
Room.where("created_at <= :time AND topic_id = :topic" , {:time => 6.minutes.ago, :topic =>topic.id}).destroy_all
selected_room = Room.where("#{params[:position]} is null and topic_id = '#{topic.id}'")
selected_room = selected_room.shuffle.first
# if there isn't one, create one. if there is, fill the position
if !selected_room
session_id_string = OTSDK.createSession.to_s
selected_room = topic.rooms.create({ session_id: session_id_string, short_session_id: self.short_session(session_id_string), "#{params[:position]}" => true})
else
selected_room.update_attribute params[:position], true
end
end
# return the room
selected_room
end
def self.room_with_session_or_next_available(received_session_id, topic, params)
room = find_room_with_session(received_session_id)
if room.nil?
room = create_or_join(topic, params)
end
room
end
def self.find_room_with_session(received_session_id)
Room.where("short_session_id = ?", received_session_id).first
end
def close(position, observer_id)
if position == 'observe'
if observer_id.nil?
Observer.where("room_id =?", self.id).first.destroy
else
Observer.find(observer_id).destroy
end
else
update_attribute position, nil unless self.nil?
end
self.destroy if (agree.nil? and disagree.nil? and !self.nil?)
end
def add_observer
observers.create
end
def self.find_observable_room(topic)
room = Room.where("(agree is not null and disagree is not null) and topic_id = ?", topic.id).shuffle.first
return room unless room.nil?
room = Room.where("(agree is not null or disagree is not null) and topic_id = ?", topic.id).shuffle.first
room
end
def self.publisher_token(session)
OTSDK.generateToken :session_id => session, :role => OpenTok::RoleConstants::PUBLISHER
end
def self.subscriber_token(session)
OTSDK.generateToken :session_id => session, :role => OpenTok::RoleConstants::SUBSCRIBER
end
def self.short_session(session)
session.to_s[-7..-2]
end
end
| true |
478e7176ad351184c9435237b8f7788ae3c08dea | Ruby | TomJamesDuffy/Boris | /spec/van_spec.rb | UTF-8 | 1,233 | 2.75 | 3 | [] | no_license | require 'van'
describe Van do
let(:dummy_bike_working) { double :dummy_bike_working, working: true }
let(:dummy_bike_not_working) { double :dummy_bike_working, working: false }
describe ':get_instructions' do
it 'raises an error if input is not in an appropriate format' do
expect{ subject.get_instructions("location", "is_working", "action") }.to raise_error(StandardError)
end
end
describe ':select_bikes' do
it 'identifies working bikes to be loaded' do
dummy_station = double(:bikes => [].push(dummy_bike_working))
subject.get_instructions(dummy_station, true, "pickup")
expect(subject.select_bikes.length).to eq(1)
end
end
describe ':load_bikes_at_location' do
it 'adds bikes to vans storage' do
dummy_array = []
dummy_station = double(:bikes => dummy_array.push(dummy_bike_working))
subject.get_instructions(dummy_station, true, "pickup")
subject.select_bikes
subject.load_bikes_into_van
expect(subject.bikes.length).to eq(1)
end
end
# Tests to be written for :remove_bikes_at_location, drop_bikes_at_location, remove_bikes_from_van.
# Tests to be written to confirm that error testing is working as expected.
end
| true |
9bf64d33fe39a1a757536896f697178122b9fdcf | Ruby | bryouf22/magic | /app/models/deck.rb | UTF-8 | 2,878 | 2.515625 | 3 | [] | no_license | # == Schema Information
#
# Table name: decks
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# name :string
# colors :integer is an Array
# format_ids :integer is an Array
# user_id :integer
# status :integer default("personal"), not null
# slug :string
# color_ids :integer is an Array
# card_number :integer
# card_in_main_deck :integer
# is_public :boolean default(FALSE)
# description :text
# category_id :integer
# format :integer default(0), not null
# complete_percent :integer
#
class Deck < ApplicationRecord
include Bitfields
belongs_to :user
belongs_to :category, optional: true
has_many :card_decks, dependent: :destroy
has_many :cards, through: :card_decks
enum status: { personal: 1, published: 2 }
bitfield :format, 1 => :modern, 2 => :legacy, 4 => :standard, 8 => :commander, 16 => :pioneer
bitfield :color, 1 => :black, 2 => :red, 4 => :blue, 8 => :green, 16 => :white
scope :publics, -> { where(is_public: true) }
scope :complets, -> { where(complete_percent: 100) }
validates :name, presence: { message: 'Vous devez renseigner un nom.' }
validates :name, uniqueness: { scope: :user_id, message: 'Vous possèdez déjà un deck avec ce nom !' }
validates :user_id, presence: true
before_save :update_slug, :set_colors, :set_card_numbers, :set_card_in_main_deck, :update_complete_percent # , :validate_formats
def colors
colors = []
(color_ids || []).each do |id|
colors << Color::COLORS_MAPPING.invert[id].to_s
end
colors
end
def generate_draft
@draft = Draft::DraftFromCubeGenerator.call(deck_id: params['id']).tirages
end
def validate_formats
Format::Validator.call(deck: self)
end
def formats
bitfield_values(:format).collect { |n, v| n if v }.compact.join(', ').humanize
end
def missing_cards
CardCollection::RetrieveMissingCardFromDeck.call(user_id: user.id, deck_id: id).result
end
private
def set_card_numbers
self['card_number'] = card_decks.sum { |card_deck| card_deck.occurences_in_main_deck + card_deck.occurences_in_sideboard }
end
def set_card_in_main_deck
self['card_in_main_deck'] = card_decks.sum(&:occurences_in_main_deck)
end
def set_colors
c_ids = []
cards.collect(&:colors).flatten.uniq.each do |color_name|
c_ids << Color.__send__(color_name)
end
self['color_ids'] = c_ids
end
def update_complete_percent
self['complete_percent'] = Deck::CalculatePercentComplete.call(deck_id: id).complete_percent unless new_record?
end
def update_slug
self[:slug] = name.parameterize
end
end
| true |
ea78284301948414ea7999ce6564080755d4af6d | Ruby | shouya/revo-old | /lib/revo/value.rb | UTF-8 | 820 | 2.734375 | 3 | [] | no_license |
module Revo
class Value
def atom?
true
end
def list?
!atom?
end
alias_method :pair?, :list?
def is_true?
true
end
def is_false?
!is_true?
end
def code?
false
end
def data?
!code?
end
def null?
false
end
def ==(another)
raise RuntimeError, "Not implmented `==' for" <<
" #{inspect}::#{self.class.to_s}"
end
def inspect
"unimplemented 'inspect' for <#{self.class.to_s}::#{self.object_id}>"
end
def to_s
"unimplemented 'to_s' for <#{self.class.to_s}::#{self.object_id}>"
end
def type_string
self.class.to_s
.sub(/.*::/, '')
.each_char.inject('') {|s,x| s << (x=~/[a-z]/ ? x : "-#{x.downcase}")}
.sub(/^-/, '')
end
end
end
| true |
1602a5c96e0ef7e5c532bf2343275c395f22bb71 | Ruby | xaop/xmpp_bot | /lib/XMPP.rb | UTF-8 | 11,262 | 2.671875 | 3 | [] | no_license | require 'rubygems'
require 'xmpp4r'
require 'xmpp4r/roster'
require 'xmpp4r/vcard'
require 'drb'
require 'yaml'
require 'mutex_m'
class Jabber::JID
##
# Convenience method to generate node@domain
def to_short_s
s = []
s << "#@node@" if @node
s << @domain
return s.to_s
end
end
module XMPPBot
#to connect the service with the bot
def connect host, port, handler
DRb.start_service
#Get remote XMPPBot
@bot = DRbObject.new_with_uri "druby://#{host}:#{port}"
#Pass MessageHandler
@bot.set_handler handler
@bot
end
module_function :connect
#Abstract class for messagehandling
class MessageHandler
include DRbUndumped
def initialize
end
def handle from, message
[:return, "Received message: #{message}"]
end
def commands
"none"
end
def terminate
exit
end
end
#Simple MessageHandler
# => looks up message in dictionary and calls associated method on stored object
class MethodDelegate < MessageHandler
def initialize obj, dict
@obj = obj
@dict = dict
end
def handle from, message
[:return, if @dict[message.to_sym]
@obj.send(@dict[message.to_sym]).to_s
else
"Unknown method"
end]
end
end
#Bot
# * Processes incoming and outgoing messages
# if necessary delegating them to a handler
# * Handles subscriptions on servicemessages
# * Starts/Stops service via messagehandler
#
class XMPPBot
include Mutex_m
#name: botname
#config: {:username => username,
# :password => password,
# :host => host,
# :auto_start => true,
# :start_delay => seconds,
# :start_command => "god -c monitor.rb"}
#
#handler: MessageHandler, usually not provided on creation
#stop_thread: false if scripts needs to keep running after setup of Bot
#
def initialize(name, config, handler=nil, stop_thread=true)
@name = name
@start_com = config[:start_command]
@handler = handler
@friends_sent_to = []
@friends_online = {}
@friends_in_need = []
@mainthread = Thread.current
@config = config
login(config[:username], config[:password], config[:host])
listen_for_subscription_requests
listen_for_presence_notifications
listen_for_messages
send_initial_presence
poll_status if config[:poll_status]
#keep_alive
Thread.new do
sleep(config[:start_delay]) if config[:start_delay]
start_service if config[:auto_start]
end
at_exit do
begin
if bool_status
@handler.terminate
end
rescue
#just quit
end
end
Thread.stop if stop_thread
end
#connect to jabberserver
def login(username, password, host)
@jid = Jabber::JID.new("#{username}/#{@name}")
@client = Jabber::Client.new(@jid)
@client.connect host
@client.auth(password)
end
#stops serving
def logout
@mainthread.wakeup
@client.close
end
#sets messagehandler
def set_handler handler
@handler = handler
@running = true
change_info
send_message_all "Service initiated"
end
#services that are failing, can remove the handler
#so the XMPPBot knows something went wrong
def remove_handler
@handler = nil
@running = false
change_info
send_message_all "Service terminating..."
end
# just a 'keepalive' thread to keep the jabber server in touch
# sends a presence entity every 30 seconds
#def keep_alive
#Thread.new do
# while true do
# @client.send(Jabber::Presence.new.set_status(@status))
# sleep 30
#end
#end
#end
#checks every 10 seconds the state of the registered service
# => this way, the online status of the bot can be altered when
# the service goes down
def poll_status
Thread.new do
while true do
real_stat
sleep 10
end
end
end
#notify server of presence
def send_initial_presence
@status = "#{@name} is online"
@client.send(Jabber::Presence.new.set_status(@status))
end
#handles subscription requests
def listen_for_subscription_requests
@roster = Jabber::Roster::Helper.new(@client)
@roster.add_subscription_request_callback do |item, pres|
if pres.from.domain == @jid.domain
log "ACCEPTING AUTHORIZATION REQUEST FROM: " + pres.from.to_s
@roster.accept_subscription(pres.from)
end
end
end
#handles incoming messages
def listen_for_messages
@client.add_message_callback do |m|
if m.type != :error
if !@friends_sent_to.include?(m.from)
send_message m.from, "Welcome to #{@name}\nUse help to view commands"
@friends_sent_to << m.from
end
begin
case m.body.to_s
#subscribe to messages from this bot
when 'yo'
if @friends_in_need.include? m.from
send_message m.from, "We already said hello"
else
@friends_in_need << m.from
send_message m.from, "Subscribed to logging"
end
#unsubscribe from messages from this bot
when 'bye'
if @friends_in_need.delete(m.from)
send_message m.from, "Unsubscribed from logging"
else
send_message m.from, "You say goodbye even before greeting me (yo)!"
end
#request status of bot
when 'cava?'
send_message m.from, status
#print available commands
when 'help'
send_message m.from, commands
#run start command on commandline
when 'init'
if !bool_status
send_message_all "[#{m.from.to_short_s}]Initiating...", m.from
start_service
else
send_message m.from, "Already running"
end
#terminate via messagehandler
when 'terminate'
if bool_status
send_message_all "[#{m.from.to_short_s}]Terminating...", m.from
stop_service
else
send_message m.from, "Not running"
end
#user is probably composing a message
when ''
#pass message to messagehandler
else
puts "RECEIVED: " + m.body.to_s
if bool_status
mes = process(m)
if mes.kind_of? Array
to, mes = mes
else
to = :return
end
case to
when :all
send_message_all mes, m.from
when :return
send_message m.from, mes
else
send_message to, mes
end
else
send_message m.from, status
send_message m.from, "Use help to view commands"
end
end
rescue => e
m = "Exception: #{e.message}"
log m
send_message m.from, m
end
else
log [m.type.to_s, m.body].join(": ")
end
end
end
#handles presence-notifications of friends
def listen_for_presence_notifications
@client.add_presence_callback do |m|
case m.type
when nil # status: available
log "PRESENCE: #{m.from.to_short_s} is online"
@friends_online[m.from.to_short_s] = true
when :unavailable
log "PRESENCE: #{m.from.to_short_s} is offline"
@friends_online[m.from.to_short_s] = false
@friends_in_need.delete(m.from)
@friends_sent_to.delete(m.from)
end
end
end
#obvious
def send_message(to, message)
log("Sending message to #{to}")
msg = Jabber::Message.new(to, message)
msg.type = :chat
@client.send(msg)
end
#send the message to all subscripted users
def send_message_all(message, other=nil)
@friends_in_need.map { |friend| send_message(friend, message) }
send_message(other, message) if(other && !@friends_in_need.include?(other))
end
#blah
def change_info()
if vcard_config = @config[:vcard]
stat = "#{@name} - #{status}"
if !@set_photo && vcard_config[:photo]
@photo = IO::readlines(vcard_config[:photo]).to_s
@avatar_hash = Digest::SHA1.hexdigest(@photo)
end
Thread.new do
vcard = Jabber::Vcard::IqVcard.new({
'NICKNAME' => @name,
'FN' => vcard_config['fn'],
'URL' => vcard_config['url'],
'PHOTO/TYPE' => 'image/png',
'PHOTO/BINVAL' => Base64::encode64(@photo)
})
Jabber::Vcard::Helper::set(@client, vcard)
end
presence = Jabber::Presence.new(:chat, stat)
x = presence.add(REXML::Element.new('x'))
x.add_namespace 'vcard-temp:x:update'
x.add(REXML::Element.new('photo')).text = @avatar_hash
@client.send presence
@set_photo = true
@status = stat
end
end
#obvious
def log(message)
puts(message) if Jabber::debug
end
private
def start_service
@start_com.call if @start_com
end
def stop_service
h = @handler
@handler = nil
@running = false
change_info
h.terminate
end
#returns available commands
def commands
c = <<HERE
\nBot Commands
-------------
yo: subscribe to messages of bot
bye: unsubscribe from messages of bot
cava?: ask for status bot
init: start service
terminate: stop service\n
HERE
if bool_status
c + @name + " Commands\n----------------\n" + @handler.commands
else
c
end
end
#checks availability of services
def bool_status
real_stat == :up
end
#checks state of services
# :up : running
# :just_down : unexpected down
# :down : already known down
# :unmonitored : no registered process
def real_stat
@handler ? begin
@handler.to_s
:up
rescue
if @running
lock
@running = false
change_info
send_message_all "Service went down"
unlock
:just_down
else
:down
end
end : :unmonitored
end
#checks availability of services and returns appropriate message
def status
case real_stat
when :up
"Service up"
when :just_down
"Service down"
when :down
"Service down"
when :unmonitored
"No process registered for monitoring"
end
end
#pass the message to the messagehandler
def process m
@handler.handle(m.from.to_short_s, m.body)
end
end
end | true |
37a9b7a70804f113ba1ece2ae32ac034c67b49dc | Ruby | michaeljohnsargent/complete_ror_developer | /S2/section2_19_working_with_numbers.rb | UTF-8 | 696 | 4.34375 | 4 | [] | no_license | # puts 1 + 2
# x = 5
# y = 10
# puts y / x
# puts "I am a line"
# puts "-"*20
# puts "I am a different line"
# 20.times { print "-" }
# #20.times { puts "hi" }
# #20.times { puts rand(10) }
# x = "5".to_i
# p x
# p x.to_f
# p "10".to_f
puts "Simple calculator"
25.times { print "-" }
puts "\nEnter the first number"
num_1 = gets.chomp
puts "Enter the second number"
num_2 = gets.chomp
puts "The first number multiplied by the second is #{ num_1.to_i * num_2.to_i }"
puts "The first number divided by the second is #{ num_1.to_i / num_2.to_i } and the remainder is #{ num_1.to_i.modulo( num_2.to_i ) } "
puts "The first number substracted by the second is #{ num_1.to_i - num_2.to_i }"
| true |
6b233297e4c52c9ef6a2fef68d03569d4b738ec1 | Ruby | leerivera/oo-relationships-practice | /app/models/dessert.rb | UTF-8 | 544 | 3.1875 | 3 | [] | no_license | class Dessert
attr_accessor :name, :bakery
####when its says "belongs to" put a attr to ref
#the class it belongs too. the attr reader on dessert
### is the sticker that states it's relationship
### dessert does not need ingredients because ingredients belong to it
### and my sticker is on ingredi
@@all = []
def initialize(name, bakery)
@name = name
@bakery = bakery
@@all << self
end
def self.all
@@all
end
def dessert_calories
Ingredient.all.select{|cal_obj| cal_obj.dessert == self}
end
end | true |
256593d419001f7631ba175527fb5ac21248de76 | Ruby | sanjsanj/ruby-shop | /lib/models/shop.rb | UTF-8 | 587 | 2.84375 | 3 | [] | no_license | require 'json'
require_relative 'cart'
require_relative 'products'
class Shop
attr_accessor :cart, :products
def initialize(cart: Cart.new, products: Products.new)
@products = products
@cart = cart
end
def shop_products
products.data
end
def add_to_cart(id:)
cart.add_item(item: item(id: id))
products.decrement_stock(id: id)
end
def cart_total
cart.total
end
private
def item(id:)
products.find(id: id)
end
def default_cart
to_return ||= Cart.new
end
def default_products
to_return ||= Products.new
end
end
| true |
a79ac925ec81b44eb8a057066579d6dd583aab42 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/anagram/e1cd91b665c74ef7a22f16a6bd25bbfc.rb | UTF-8 | 366 | 3.84375 | 4 | [] | no_license | class Anagram
attr_reader :word_to_match
def initialize(word_to_match)
@word_to_match = word_to_match.downcase
end
def match(words)
words.select { |word| anagram?(word) }
end
private
def anagram?(word)
word_to_match.chars.sort == word.chars.sort unless identical?(word)
end
def identical?(word)
word == word_to_match
end
end
| true |
760ce81f12d7abd6cc29993cb505cac9c8696ff3 | Ruby | kingsleyh/redfighter | /app/models/fight_bar.rb | UTF-8 | 269 | 2.65625 | 3 | [] | no_license | class FightBar < ActiveRecord::Base
belongs_to :player
def slots
[slot_1,slot_2,slot_3,slot_4,slot_5].map{|i| item(i)}
end
private
def item(slot)
a = FightItem.where(:id => slot)
a.empty? ? OpenStruct.new(:name => 'empty') : a.first
end
end
| true |
e29fb35dd8015d5b9630d07f9db25b1c5f263588 | Ruby | dmagro/activerecord-import-example | /lib/tasks/import_records.rake | UTF-8 | 1,779 | 3 | 3 | [] | no_license | require "benchmark"
namespace :import do
BOOKS_PATH = "#{Rails.public_path}/books/"
def read_books
books = []
Dir.foreach(BOOKS_PATH) do |item|
next if item == '.' or item == '..'
puts "Reading #{item}...".green
books << read_book(item)
end
books
end
def read_book(file_name)
file_path = "#{BOOKS_PATH}/#{file_name}"
file = File.open(file_path, "rb")
book_text = file.read
Book.new(book_contents(book_text))
end
def book_contents(book_text)
book_details = book_details(book_text)
book_details.merge({ sentences: book_sentences(book_text) })
end
def book_details(book_contents)
{
title: /Title:(.+)/.match(book_contents)[1].strip,
author: /Author:(.+)/.match(book_contents)[1].strip,
language: /Language:(.+)/.match(book_contents)[1].strip
}
end
def book_sentences(book_contents)
puts "Extract Sentences text".yellow
sentences = extract_sentences(book_contents)
puts "Create Sentences".yellow
sentences_records = sentences.reduce([]){|result, sentence_text| result << Sentence.new(content: sentence_text)}
puts "Extracted #{sentences_records.count} sentences"
sentences_records
end
def extract_sentences(book_contents)
PragmaticSegmenter::Segmenter.new(text: book_contents.force_encoding('UTF-8'), doc_type: 'txt').segment
end
desc 'Import Book from files.'
task books: :environment do
time = Benchmark.bmbm do |x|
books = []
x.report("Extract Books:"){ books = read_books }
x.report("Regular Import:"){ books.each{ |book| book.save } }
x.report("Delete Records:"){Sentence.destroy_all; Book.destroy_all}
x.report("ActiveRecord Import:"){ Book.import(books, recursive: true) }
end
end
end
| true |
1c51e52fc07c5eeb74a7b49b578fd9db213add5e | Ruby | Earth35/basic_ruby_projects | /stock_picker.rb | UTF-8 | 720 | 4.0625 | 4 | [] | no_license | def stock_picker (input)
max_income = 0
buying_day = nil
selling_day = nil
0.upto(input.length-2) do |i|
current_price = input[i]
(i+1).upto(input.length-1) do |j|
profit = input[j] - input[i]
if (profit > max_income)
buying_day = i
selling_day = j
max_income = profit
end
end
end
return [buying_day, selling_day]
end
puts "Enter prices for each day separated by commas (Default example: 17,3,6,9,15,8,6,1,10)"
price_array = gets.chomp
if price_array == ""
price_array = [17,3,6,9,15,8,6,1,10]
else
price_array = price_array.split(",")
price_array.each_index do |x|
price_array[x] = price_array[x].to_i
end
end
puts "Best days to buy & sell: #{stock_picker(price_array)}" | true |
6da77cf03ca891bd030564151826736306003dc5 | Ruby | nozpheratu/tournament_sandbox | /test.rb | UTF-8 | 120 | 3.046875 | 3 | [] | no_license | h1 = {:stuff => [1,2,3]}
h2 = h1.dup
h2[:stuff].delete_at(0)
puts h1 #=> {:stuff=>[2, 3]}
puts h2 #=> {:stuff=>[2, 3]}
| true |
bcbc8a8b3fc6562b4123d01f0642d9b9ec43dcd0 | Ruby | Hollyberries/deli-counter-onl01-seng-pt-050420 | /deli_counter.rb | UTF-8 | 616 | 3.765625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | katz_deli = []
def line(line_array)
if line_array.length == 0
puts "The line is currently empty."
else
line_prompt = "The line is currently: "
line_array.each.with_index(1) do |person, line_number|
line_prompt += "#{line_number}. #{person} "
end
puts line_prompt.strip
end
end
def take_a_number(katz_deli, name)
katz_deli.push(name)
puts "Welcome, #{name}. You are number #{katz_deli.length} in line."
end
def now_serving(name)
if name.length == 0
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{name.first}."
name.shift
end
end
| true |
27d7471f9575582b1af00034411a5682983d71d9 | Ruby | urzp/TicTacToe | /main body.rb | UTF-8 | 347 | 2.71875 | 3 | [] | no_license | include TicTacToe
game=Game_place.new
a_man=Human.new
comp=Computer.new
puts "********************************"
coin_toss(a_man, comp, game)
game.draw_board
puts "********************************"
while !game.stop do
current_player = game.who_turn?
player_chose = current_player.turn(game.board)
game.turn(player_chose, current_player)
end
| true |
2cb4533d6e21b214b2103cd1512a4749df0476a3 | Ruby | bharatagarwal/launch-school | /100_back-end_prep/intro-to-programming/10_exercises/10.rb | UTF-8 | 90 | 2.96875 | 3 | [] | no_license | hash = {e: [1,2], b: [2,3]}
p hash[:b]
array = [{a: 1, b: 2}, {c: 3, d:4}]
p array[0][:b] | true |
c00abcb7ff0321a2f7a15abac9c555d029e22af6 | Ruby | jennli/quiz1_jan_25 | /question_2_stack_queue.rb | UTF-8 | 930 | 4.40625 | 4 | [] | no_license | # Stacks & Queues: Explain the difference between a stack and a queue. Write a Ruby class called Stack and another Ruby class called Queue. Each class should have two instance methods `add` and `remove` to add an element to the stack or queue or to remove an element from the stack or queue. Make sure that each class behaves properly as per definitions of stacks and queues.
# Stack is a LIFO data structure, meaning the last element added to the stack will be the first one removed from it.
# Queue is a FIFO data structure, meaning the first element added to the stack will be the first one removed from it
class Stack
attr_accessor :stack
def initialize
@stack = []
end
def add(obj)
stack.push(obj)
end
def remove
stack.pop
end
end
class Queue
attr_accessor :queue
def initialize
@queue = []
end
def add(obj)
queue.push(obj)
end
def remove
queue.shift
end
end
| true |
4278bb91b1cc96e7061be6815bba675cd7312145 | Ruby | sivanpatel/battle_ships-1 | /lib/board.rb | UTF-8 | 255 | 2.75 | 3 | [] | no_license | # require_relative 'battle_ship'
require_relative 'grid'
class Board
attr_accessor :placed_ships
def initialize
@placed_ships = []
end
# def total_ships -- use for getting locations
# @placed_ships.map { |ship| ship.size }
# end
end
| true |
0459f1817759dae0ce0b4e33bef8f2760da293b6 | Ruby | ghas-results/hammerspace | /spec/support/write_concurrency_test.rb | UTF-8 | 1,189 | 2.859375 | 3 | [
"MIT"
] | permissive | module WriteConcurrencyTest
# Initialize n hashes (of joyful nonsense), fork one process for each. Have
# them madly write their hash, and flush (repeat many, many times). While
# this is happening, read from the hammerspace. It should contain one of the
# n original hashes. Though which one I shall never tell.
def run_write_concurrency_test(path, options, concurrency = 10, iterations = 10, size = 10)
pids = []
concurrency.times do |id|
pids << fork do
iterations.times do
hash = Hammerspace.new(path, options)
size.times { |i| hash[i.to_s] = id.to_s }
hash.close
end
end
end
# Wait for first hash to be written, otherwise our hash.size expectations will fail.
sleep(0.5)
iterations.times do
hash = Hammerspace.new(path, options)
hash_size = hash.size
raise "hash.size == #{hash_size}, expected #{size}" unless hash_size == size
size.times do |i|
unless hash[i.to_s] == hash['0']
raise "hash[#{i.to_s}] == #{hash[i.to_s]}, expected #{hash['0']}"
end
end
hash.close
end
pids.each { |pid| Process.wait(pid) }
end
end
| true |
773f16c75a15e8f819cc4817f197a64213026701 | Ruby | chad-tung/week2_day3_snakes_ladders | /specs/dice_spec.rb | UTF-8 | 280 | 2.6875 | 3 | [] | no_license | require "minitest/autorun"
require "minitest/rg"
require_relative "../dice"
class TestDice < MiniTest::Test
def setup()
@dice = Dice.new(6)
end
def test_roll_dice()
result = (1..6).include?(@dice.roll())
assert_equal(true, result)
end
end
| true |
1cf4b9b550ef2d889e73f6bc19aaa814fa896406 | Ruby | tomerovadia/Battleship | /player.rb | UTF-8 | 6,446 | 3.65625 | 4 | [] | no_license | require_relative 'improved_board.rb'
require_relative 'improved_ship.rb'
require 'byebug'
require 'colorize'
class Player
attr_reader :board
attr_accessor :name, :ships, :game
def initialize(board = Board.new)
@board = board
@ships = []
end
def update_ships
@ships = @ships.select do |ship|
!(ship.sunk?)
end
end
def create_ship(first_end, second_end, ship_type, ship_size)
new_ship = Ship.new(self,first_end, second_end)
@ships << new_ship
new_ship.christen(@board)
end
def no_ships?
@ships.empty?
end
end
class HumanPlayer < Player
def ready?
gets
true
end
def end_turn
gets
end
def set_name
puts "What's your name?"
@name = gets.chomp
end
def set_color
puts "#{@name}, what color do you want to be?:"
print "Options: "
String.colors.each {|color| print color.to_s + " "}
puts
selected_color = gets.chomp.downcase
until String.colors.include?(selected_color.to_sym)
puts "Please select a valid color."
selected_color = gets.chomp.downcase
end
@board.color = selected_color
end
def get_play(board)
puts "Where do you want to attack? (Gimme two coordinates)"
begin
coordinates_array = HumanPlayer.send(:format_user_input,gets.chomp)
if !(board.in_range?(coordinates_array))
puts "Coordinates not in range!"
raise "Coordinates must exist in grid"
end
coordinates_array
rescue
puts "Try again:"
retry
end
end
def get_ship(ship_type, target_size)
puts "\n#{@name}, let's place your #{ship_type} (#{target_size}x1)."
begin
puts "Enter coordinates for the first end of your #{ship_type}."
first_end = HumanPlayer.send(:format_user_input,gets.chomp)
rescue
sleep(2)
puts "Try again:"
retry
end
begin
puts "Enter coordinates for the other end of your #{ship_type}."
second_end = HumanPlayer.send(:format_user_input,gets.chomp)
rescue
sleep(2)
puts "Try again:"
end
[first_end, second_end]
end
def place_ship(ship_type)
target_size = Ship::SHIPS[ship_type]
ends = get_ship(ship_type, target_size)
first_end,second_end = *ends
coordinates = @board.coordinates_in_between(first_end,second_end)
until coordinates && @board.coordinates_in_range?(coordinates) && !(@board.spot_taken?(coordinates)) && ship_size_ok?(target_size, coordinates)
ends = get_ship(ship_type,target_size)
first_end, second_end = *ends
coordinates = @board.coordinates_in_between(first_end,second_end)
end
create_ship(first_end, second_end, ship_type, coordinates.length)
end
def place_all_ships
Ship::SHIPS.keys.each do |ship_type|
place_ship(ship_type)
@board.display(false)
end
puts "\n"
end
def ship_size_ok?(ship_size, coordinates)
if ship_size != coordinates.length
puts "\nERROR: NEED A #{ship_size}x1 SHIP!"
sleep(2)
return false
end
true
end
private
def self.format_user_input(str)
coordinates = str.scan(/\d+/)
# Make sure only two coordinates were given
if coordinates.length != 2
puts "Give me only two coordinates!" if coordinates.length > 2
puts "I need two coordinates!" if coordinates.length < 2
raise "Input must contain two digits"
end
[coordinates[0].to_i, coordinates[1].to_i]
end
end
class ComputerPlayer < Player
def ready?
true
end
def end_turn
# intentionally blank
end
def set_name
puts "What's your name?"
puts "Barack Obama"
@name = "Barack Obama"
end
def set_color
puts "#{@name}, what color do you want to be?:"
print "Options: "
String.colors.each {|color| print color.to_s + " "}
puts
puts "red"
@board.color = "red"
end
def get_play(board)
hash_of_possible_positions = @game.other_player.board.hash_of_positions_and_state.select {|pos,state| !state || state == :s}
random_possible_position = hash_of_possible_positions.keys.sample
random_possible_position
end
def get_ship(ship_type, target_size)
coordinates = []
# until we get coordinates that are all in range and aren't taken
until !(coordinates.empty?) && coordinates.all? {|coordinate| @board.in_range?(coordinate)} && !(@board.spot_taken?(coordinates))
start_end_coordinates = []
# get a random nil position
hash_of_nil_positions = @board.hash_of_positions_and_state.select {|pos,state| !state}
nil_positions = hash_of_nil_positions.keys
start_coordinate = nil_positions.sample
start_end_coordinates << start_coordinate
end_coordinate = [start_coordinate[0],start_coordinate[1]]
inc_or_dec = rand(2)
if inc_or_dec == 1
end_coordinate[rand(2)] += target_size-1
else
end_coordinate[rand(2)] -= target_size-1
end
start_end_coordinates << end_coordinate
coordinates = @board.coordinates_in_between(start_coordinate,end_coordinate)
end
start_end_coordinates
end
def place_ship(ship_type)
target_size = Ship::SHIPS[ship_type]
ends = get_ship(ship_type, target_size)
new_ship = Ship.new(self,ends[0], ends[1])
@ships << new_ship
new_ship.christen(@board)
end
def place_all_ships
Ship::SHIPS.keys.each do |ship_type|
place_ship(ship_type)
end
@board.display(false)
puts "\n"
end
end | true |
086fa7caae305323b3b85602e4a0d42c943c6844 | Ruby | chocopowwwa/ssbe-wsdl | /vendor/gems/resourceful-0.3.1/spec/resourceful/header_spec.rb | UTF-8 | 982 | 2.75 | 3 | [
"MIT"
] | permissive | require 'pathname'
require Pathname(__FILE__).dirname + '../spec_helper'
require 'resourceful/header'
describe Resourceful::Header do
it "should capitalize on all accesses" do
h = Resourceful::Header.new("foo" => "bar")
h["foo"].should == "bar"
h["Foo"].should == "bar"
h["FOO"].should == "bar"
h.to_hash.should == {"Foo" => "bar"}
h["bar-zzle"] = "quux"
h.to_hash.should == {"Foo" => "bar", "Bar-Zzle" => "quux"}
end
it "should capitalize correctly" do
h = Resourceful::Header.new
h.capitalize("foo").should == "Foo"
h.capitalize("foo-bar").should == "Foo-Bar"
h.capitalize("foo_bar").should == "Foo-Bar"
h.capitalize("foo bar").should == "Foo Bar"
h.capitalize("foo-bar-quux").should == "Foo-Bar-Quux"
h.capitalize("foo-bar-2quux").should == "Foo-Bar-2quux"
end
it "should be converted to real Hash" do
h = Resourceful::Header.new("foo" => "bar")
h.to_hash.should be_instance_of(Hash)
end
end
| true |
5c1783a176f3c3f149a6ea4477f86e1084d1af62 | Ruby | dcolebatch/pacer | /lib/pacer/pipe/group_pipe.rb | UTF-8 | 2,391 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | module Pacer::Pipes
class GroupPipe < RubyPipe
def initialize
super()
@next_key = nil
@key_pipes = []
@values_pipes = []
@current_keys = []
@current_values = nil
end
def setUnique(bool)
@unique = unique
@groups = {}
end
def addKeyPipe(from_pipe, to_pipe)
@key_pipes << prepare_aggregate_pipe(from_pipe, to_pipe)
end
def addValuesPipe(name, from_pipe, to_pipe)
@values_pipes << [name, *prepare_aggregate_pipe(from_pipe, to_pipe)]
end
def hasNext
!!@nextKey or super
rescue NativeException => e
if e.cause.getClass == Pacer::NoSuchElementException.getClass
raise e.cause
else
raise e
end
end
protected
def prepare_aggregate_pipe(from_pipe, to_pipe)
expando = ExpandablePipe.new
expando.setStarts java.util.ArrayList.new.iterator
from_pipe.setStarts(expando)
agg_pipe = com.tinkerpop.pipes.sideeffect.AggregatePipe.new java.util.LinkedList.new
cap_pipe = com.tinkerpop.pipes.transform.SideEffectCapPipe.new agg_pipe
agg_pipe.setStarts to_pipe
cap_pipe.setStarts to_pipe
[expando, cap_pipe]
end
def processNextStart
while true
if @current_keys.empty?
element = next_element
@current_keys = get_keys(element)
@current_values = get_values(element) unless @current_keys.empty?
else
return Pacer::Group.new(@current_keys.removeFirst, @current_values)
end
end
rescue NativeException => e
if e.cause.getClass == Pacer::NoSuchElementException.getClass
raise e.cause
else
raise e
end
end
def get_keys(element)
array = java.util.LinkedList.new
@key_pipes.each do |expando, to_pipe|
array.addAll next_results(expando, to_pipe, element)
end
array
end
def get_values(element)
@values_pipes.map do |name, expando, to_pipe|
[name, next_results(expando, to_pipe, element)]
end
end
def next_results(expando, pipe, element)
pipe.reset
expando.add element, java.util.ArrayList.new, nil
pipe.next
end
def next_element
if @next_element
element = @next_element
@next_element = nil
element
else
@starts.next
end
end
end
end
| true |
b2560494a73be6697832380e36867d2b0a2052ea | Ruby | Sheval/algos | /ruby/dijkstra.rb | UTF-8 | 1,423 | 3.484375 | 3 | [] | no_license | #!/usr/bin/env ruby
# dijkstra algo sandbox
require "pry"
require_relative "stackless"
def wrap_time message
t1 = Time.now
res = yield
t2 = Time.now
puts "#{message} - Elapsed time #{t2-t1}s"
res
end
def read_from_file file_name
File.open(file_name, 'r').each_line do |line|
line_array = line.split
yield line_array
end
end
class Dijkstra
def initialize
@graph = {}
@explored = []
@frontier = []
end
def load_vertex arr
@graph[arr.first.to_i] = arr[1..-1].reduce ([]) do |memo, pair|
head, length = pair.split(',').map(&:to_i)
memo << {head: head, length: length}
end
end
def add_vertex vertex, length
@explored[vertex] = length
@graph[vertex].each { |pair| @frontier<<[vertex, pair[:head], @explored[vertex] + pair[:length]] }
@frontier.reject! { |i, j| @explored[i] && @explored[j] }
end
def main_loop
add_vertex 1, 0
while @frontier.any? do
min_edge = @frontier.sort{ |a,b| a[2] <=> b[2] }.first
add_vertex min_edge[1], min_edge[2]
end
end
def main
wrap_time("Load graph"){ read_from_file($*[0]) { |arr| load_vertex arr } } if $*.any?
puts "Graph size - #{@graph.size} vertices"
main_loop
if @graph.size == 200
puts [7,37,59,82,99,115,133,165,188,197].map{|index| @explored[index]}.join(',')
else
p @explored
end
end
end
wrap_time("TOTAL"){Dijkstra.new.main}
| true |
460f9bd90aaa5fcff942a6897453964a128ccdb8 | Ruby | sanjsanj/mystuff | /ex08.rb | UTF-8 | 962 | 4.0625 | 4 | [] | no_license | # Define var formatter with %vars to use the same format with multiple values
formatter = "%{first} %{second} %{third} %{fourth}"
# put string of var formatter with integers defined within the hash array
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
# put string of var formatter with strings defined within the hash
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
# put string of var formatter with true/false objects defined within the hash
puts formatter % {first: true, second: false, third: true, fourth: false}
# put string of var formatter where each hash object is calling the definition of the entire var
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}
# put string of var formatter with text strings
puts formatter % {
first: "I had this thing.",
second: "That you could type up right.",
third: "But it didn't sing.",
fourth: "So I said goodnight."
}
| true |
cd606a2d4cf89c2df4ae0b826f8c93cdd535bb90 | Ruby | skanev/evans | /lib/temp_dir.rb | UTF-8 | 353 | 2.6875 | 3 | [] | no_license | module TempDir
extend self
def for(files)
Dir.mktmpdir do |dir|
dir_path = Pathname(dir)
files.each do |name, contents|
file_path = dir_path.join(name)
FileUtils.mkdir_p(file_path.dirname)
open(file_path, 'w') { |file| file.write contents.encode('utf-8') }
end
yield dir_path
end
end
end
| true |
a26aacd0ba9ba5210dd9203fc4bfe649ca5183bd | Ruby | yourpromotioncode/Numbers | /Day9_2.rb | UTF-8 | 531 | 3.1875 | 3 | [] | no_license | # ids = ['mc11' , 'dt2002']
# for id in ids do
# if id == input_id
# puts("** " + id + "!! Welcome to ITW database hub")
# exit
# end
# end
#
# puts("** Invalid ID **")
puts("[Please enter your ID] \n")
input_id = gets.chomp()
def login(id)
members = ['mc11' , 'dt2002']
for member in members do
if member == id
return true
end
end
return false
end
if login(input_id)
puts('** ' + input_id + '!! Welcome to ITW Database hub.')
else
puts('** Invalid ID **')
end
| true |
d5e9f3685a91f17a45b143dc94d2f25a8cc3ba8a | Ruby | MislavGunawardena/Back-End-Lesson01 | /excercises/problem_solving/advanced/7.rb | UTF-8 | 1,720 | 4.21875 | 4 | [] | no_license | # Method: merge
# Arguments: 2 arrays. Both containing sorted numbers.
# Side effects: None. Specifically, argument arrays should not be mutated.
# Return: A new array. Should contain all the elements of the argument arrays
# while maintaining the sorted order.
# Edge cases:
# merge([], [1, 4, 5]) == [1, 4, 5]
# merge([], []) == []
#
# Algorithm:
# array1, array2 <= arguments
# composite_array = []
# index1 = 0
# index2 = 0
# loop:
# if index1 == size of aray1
# place all items of array2 from index2 onwards on composite_array
# break
# elsif index2 == size of array2
# place all items on array1 from index1 onwards on composite array
# break
#
# first_item = array1[index1]
# second_item = array2[index2]
# if first_item <= second_item
# place first_item in composite_array
# index1 += 1
# else
# compposite_array << second_item
# index2 += 1
#
def merge(array1, array2)
composite_array = []
index1 = 0
index2 = 0
loop do
if index1 == array1.size
index2.upto(array2.size - 1) { |index| composite_array << array2[index] }
break
elsif index2 == array2.size
index1.upto(array1.size - 1) { |index| composite_array << array1[index] }
break
end
first_item = array1[index1]
second_item = array2[index2]
if first_item <= second_item
composite_array << first_item
index1 += 1
else
composite_array << second_item
index2 += 1
end
end
composite_array
end
p merge([1, 5, 9], [2, 6, 8]) == [1, 2, 5, 6, 8, 9]
p merge([1, 1, 3], [2, 2]) == [1, 1, 2, 2, 3]
p merge([], [1, 4, 5]) == [1, 4, 5]
p merge([1, 4, 5], []) == [1, 4, 5] | true |
05a6cb082e4878fea6c658e5d57a249f8f898545 | Ruby | AnguillaJaponica/Ruby_Library_For_Contests | /ABC/ABC083/C.rb | UTF-8 | 88 | 3.015625 | 3 | [] | no_license | x, y = gets.split.map(&:to_i)
res = 1
while 2 * x <= y
res += 1
x *= 2
end
puts res | true |
93271a179080a7a6007d16ccf4795187025ee37d | Ruby | yiyi1026/projecteuler_ruby | /p1-p50/p46.rb | UTF-8 | 392 | 2.984375 | 3 | [] | no_license | #P46
require 'prime'
#a=Time.now
def p46_single(n)
return nil if n%2 == 0 || Prime.prime?(n)
k=Prime.each(n-2).to_a.reverse
k.pop
for i in k
return i if (n-i)%2==0 && 2*(Math.sqrt((n-i)/2).to_i)**2==n-i
end
return false
end
def p46_multi(n)
i=9
while i<=n
l=p46_single(i)
return i if l==false
i+=2
end
return false
end
p p46_multi(10000)
#p Time.now-a
| true |
c982a18b7729e6f846f042b29a2a5c44cbf12e85 | Ruby | wozane/57-exercises | /making_decisions/car_problems_2.rb | UTF-8 | 1,975 | 3.21875 | 3 | [] | no_license | is_car_silent = 'Is the car silent when you turn the key?'
is_battery_corroded = 'Are the battery terminals corroded?'
battery_corroded = 'Clean terminals and try starting again.'
battery_not_corroded = 'Replace cables and try again.'
is_making_clicking_noice = 'Does the car make a clicking noise?'
making_clicking_noice = 'Replace the battery.'
does_fail_to_start = 'Does the car crank up but fail to start?'
fail_to_start = 'Check spark plug connections'
does_engine_start_and_die = 'Does the engine start and then die?'
is_fuel_injection = 'Does your car have fuel injection?'
fuel_injection = 'Get it in for service.'
no_fuel_injection = 'Check to ensure the choke is opening and closing.'
QUESTION = %W[
#{is_car_silent}
#{is_battery_corroded}
#{battery_corroded}
#{battery_not_corroded}
#{is_making_clicking_noice}
#{making_clicking_noice}
#{does_fail_to_start}
#{fail_to_start}
#{does_engine_start_and_die}
#{is_fuel_injection}
#{fuel_injection}
#{no_fuel_injection}
].freeze
def asking_question(number)
puts QUESTION[number]
gets.chomp
end
def give_answer(number)
puts QUESTION[number]
end
def yes_answer(answer)
answer == 'y'
end
def main_program
if_silent_question = asking_question(0)
if yes_answer(if_silent_question)
battery_question = asking_question(1)
if yes_answer(battery_question)
give_answer(2)
else
give_answer(3)
end
else
noice_question = asking_question(4)
if yes_answer(noice_question)
give_answer(5)
else
fail_question = asking_question(6)
if yes_answer(fail_question)
give_answer(7)
else
start_question = asking_question(8)
if yes_answer(start_question)
fuel_question = asking_question(9)
if yes_answer(fuel_question)
give_answer(10)
else
give_answer(11)
end
else
give_answer(10)
end
end
end
end
end
main_program
| true |
2649de78b5ab87c942dd78084270b190d4916cd0 | Ruby | philjdelong/pets_and_customers | /lib/groomer.rb | UTF-8 | 640 | 3.46875 | 3 | [] | no_license | class Groomer
attr_reader :name, :customers
def initialize(groomer_info)
@name = groomer_info[:name]
@customers = []
end
def add_customer(customer_info)
@customers << customer_info
end
def customers_with_balance
with_balance = @customers.find_all do |customer|
customer.outstanding_balance > 0
end
with_balance
end
def number_of(type)
pets = @customers.map do |customer|
customer.pets
end
#you need to set pets EQUAL to pets.flatten, otherwise we're not altering the original array
pets = pets.flatten
pets.count do |pet|
pet.type == type
end
end
end
| true |
b9bbfe4f35af4e0132a7b6cb3d108d3a6470e07e | Ruby | ekemi/cartoon-collections-onl01-seng-ft-012120 | /cartoon_collections.rb | UTF-8 | 644 | 3.53125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves (array)# code an argument here
# Your code here
array.each_with_index{ |name,position| puts"#{position + 1}. #{name}"}
end
def summon_captain_planet (planeteer)# code an argument here
# Your code here
planeteer.map{|cap| (cap << "!").capitalize }
end
def long_planeteer_calls (array)# code an argument here
# Your code here
array.any? {|word| word.length> 4}
end
def find_the_cheese (array)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
#(array&cheese_types).join
array.find do |type|
cheese_types.include?(type)
end
end
| true |
69722c21af8a96eb18ec25166ca8c3d99d2416f3 | Ruby | Ian-n2/homework_wk2_day1 | /homework_part_c.rb | UTF-8 | 387 | 2.890625 | 3 | [] | no_license | class Library
attr_accessor :title, :rental_details,
:student_name, :date
def initialize(input_book)
@Book = input_book
# [{
# title: = input_book,
# rental_details: = {
# student_name: = input_student,
# date: = input_date
# }
# }]
end
def book_into
if book_title == @book[:title]
return @book[:rental_details]
end
end
end
| true |
7da20b95e79823c7cf456af174445e9952e0c92f | Ruby | fontcuberta/Ironhack-Week-1 | /Day-2/Exercises/Blog.rb | UTF-8 | 2,605 | 3.84375 | 4 | [] | no_license | require "date"
require "io/console"
class Blog
def initialize
@posts = []
@total_pages = @posts.size / 3
@page = 1
end
def add_post post
@posts << post
@total_pages = @posts.size / 3
end
def publish_front_page
posts_to_show = create_front_page
posts_to_show.each do |post|
title = post.sponsored ? "*** #{post.title} ***" : post.title
puts "#{title}\n==================\n#{post.text}\n---------------------\n\n\n"
end
show_pagination
end
def create_front_page
from_post = (@page - 1) * 3
to_post = from_post + 2
@posts[from_post..to_post]
end
# Reads keypresses from the user including 2 and 3 escape character sequences.
# https://gist.github.com/acook/4190379
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
def show_pagination
pages = ""
(1..@total_pages).each do |t|
t == @page ? pages << "|#{t}| " : pages << "#{t} "
end
puts pages
puts "Use arrow keys to move between pages."
input = read_char
if input == "\e[D"
@page = (@page - 1 < 1) ? @page = @total_pages : @page -= 1
publish_front_page
elsif input == "\e[C"
@page = (@page + 1 > @total_pages) ? @page = 1 : @page += 1
publish_front_page
end
end
end
class Post
attr_reader :title, :date, :text, :sponsored
def initialize title, date, text, sponsored = false
@title = title
@date = date
@text = text
@sponsored = sponsored
end
end
blog = Blog.new
blog.add_post Post.new("Post 1", Date.new(2015, 05, 03), "This is the body of the post 1.")
blog.add_post Post.new("Post 2", Date.new(2015, 04, 04), "This is the body of the post 2.", true)
blog.add_post Post.new("Post 3", Date.new(2015, 10, 15), "This is the body of the post 3.")
blog.add_post Post.new("Post 4", Date.new(2015, 12, 02), "This is the body of the post 4.")
blog.add_post Post.new("Post 5", Date.new(2015, 03, 15), "This is the body of the post 5.")
blog.add_post Post.new("Post 6", Date.new(2015, 01, 25), "This is the body of the post 6.", true)
blog.add_post Post.new("Post 7", Date.new(2015, 06, 15), "This is the body of the post 7.")
blog.add_post Post.new("Post 8", Date.new(2015, 11, 21), "This is the body of the post 8.")
blog.add_post Post.new("Post 9", Date.new(2015, 11, 10), "This is the body of the post 9.", true)
blog.publish_front_page
| true |
ff22d9b7b778cab4446d11cceccc292207946143 | Ruby | imhimanshuk/Training | /ruby/Program/sumoddno.rb | UTF-8 | 207 | 3.484375 | 3 | [] | no_license | class Sum
def sum()
puts "Enter the number"
@no = gets.to_i
@sum = 0
while(@no!=0)
@a=@no%10
if(@a%2!=0)
@sum=@sum+@a
end
@no=@no/10
end
puts " Sum of odd numbers is #{@sum}"
end
end
obj=Sum.new
obj.sum()
| true |
30003c3118f235108ca22718aa16d4e8e390dad4 | Ruby | johnisom/ruby-challenge-problems | /medium_1/grade_school.rb | UTF-8 | 303 | 3.53125 | 4 | [] | no_license | # frozen_string_literal: true
# school class
class School
def initialize
@roster = Hash.new { |hash, key| hash[key] = [] }
end
def add(name, grade)
@roster[grade] << name
end
def to_h
@roster.sort.to_h.transform_values(&:sort)
end
def grade(num)
@roster[num]
end
end
| true |
6df79931ce07203ea5d598c3006b2dce2dc17213 | Ruby | SuzHarrison/TaskListRails | /app/controllers/tasks_controller.rb | UTF-8 | 1,857 | 2.5625 | 3 | [] | no_license | class TasksController < ApplicationController
def index
@tasks = Task.order(id: :asc)
end
def show
@task = Task.find(params[:id])
render :show
end
def new
@task = Task.new
@all_people = Person.all
end
def create #COMMON PATTERN FOR CREATE
# check_hash = task_create_params[:task]
# if check_hash[:completed_at] != nil
# check_hash[:completed_at] = DateTime.now
# end
@task = Task.new(task_create_params[:task])
if(@task.save)
redirect_to task_path(@task.id)#redirect in case user tries to post another form - brings them to entered view
else
render :new
end
end
def edit
@task = Task.find(params[:id])
@all_people = Person.all
render :edit
end
def update
@task = Task.find(params[:id])
if @task.update({:completed_at => nil}.merge(task_edit_params[:task]))
redirect_to task_path(@task.id)#redirect in case user tries to post another form - brings them to entered view
else
render :edit
end#redirect in case user tries to post another form - brings them to entered view
end
def delete
@task = Task.find(params[:id])
@task.destroy
redirect_to root_path
end
def complete
task = Task.find(params[:id])
if !task.completed
task.update(completed_at: true, completed_at: DateTime.now)
else
task.update(completed_at: false, completed_at: nil)
end
redirect_to "/"
end
private
def task_create_params#the params we want when we create a task, to sanitize and control user input
params.permit(task: [:name, :description, :person_id, :completed_status, :completed_at])#these are the only parameters that can be passed from user.
end
def task_edit_params
params.permit(task: [:name, :description, :person_id, :completed_status, :completed_at])
end
end
| true |
46d8285f16b295669cb69d08361738b1f0d9a354 | Ruby | jcramm/recordstore-inventory-manager | /lib/search.rb | UTF-8 | 2,231 | 3.015625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require './lib/models/album'
require './lib/models/artist'
class Search
VALID_TERMS_MAPPING = {
'artist' => {
'class' => Models::Artist,
'attribute' => 'name',
'sort_by' => 'artist_name',
'asc' => 1
},
'album' => {
'class' => Models::Album,
'attribute' => 'title',
'sort_by' => 'title',
'asc' => 1
},
'released' => {
'class' => Models::Album,
'attribute' => 'year',
'sort_by' => 'year',
'asc' => -1
},
'format' => {
'class' => Models::InventoryItem,
'attribute' => 'format',
'sort_by' => 'title',
'asc' => -1
}
}.freeze
def self.search(key, value)
results = {}
klass = fetch_class(key)
attribute = fetch_attribute(key)
raise ArgumentError, "Invalid query term #{key}" unless klass
klass.where({ attribute => value }, 'like').each do |result|
case result
when Models::Artist
result.albums.each { |album| results[album.id] = album }
when Models::InventoryItem
results[result.album_id] = result.album
when Models::Album
results[result.id] = result
end
end
sort(results.values, key)
end
# It was not clear to me how these were to be sorted.
# I thought at first that a multi tierd sorting was expected,
# I implemented it that way but after re-reading the spec it seemed that sorting ascending or descending
# depending on the field was the expected behavior
# See https://trello.com/c/uYovucEq/46-multi-tiered-sorting-is-not-needed-but-we-do-need-to-search-on-format
def self.sort(items, key)
asc = sort_ascending(key)
criteria = fetch_sort_term(key)
items.sort { |i, j| asc * (i.send(criteria) <=> j.send(criteria)) }
end
def self.fetch_sort_term(term)
mapping = VALID_TERMS_MAPPING[term] || {}
mapping['sort_by']
end
def self.fetch_class(term)
mapping = VALID_TERMS_MAPPING[term] || {}
mapping['class']
end
def self.fetch_attribute(term)
mapping = VALID_TERMS_MAPPING[term] || {}
mapping['attribute']
end
def self.sort_ascending(term)
mapping = VALID_TERMS_MAPPING[term] || {}
mapping['asc']
end
end
| true |
e11b78db68887909d60fa6c228e4b661755fcc16 | Ruby | DouglasAllen/code-Metaprogramming_Ruby | /raw-code/PART_II_Metaprogramming_in_Rails/gems/actionpack-4.0.0/lib/action_view/helpers/tags/check_box.rb | UTF-8 | 2,277 | 2.640625 | 3 | [
"MIT"
] | permissive | #---
# Excerpted from "Metaprogramming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ppmetr2 for more book information.
#---
require 'action_view/helpers/tags/checkable'
module ActionView
module Helpers
module Tags # :nodoc:
class CheckBox < Base #:nodoc:
include Checkable
def initialize(object_name, method_name, template_object, checked_value, unchecked_value, options)
@checked_value = checked_value
@unchecked_value = unchecked_value
super(object_name, method_name, template_object, options)
end
def render
options = @options.stringify_keys
options["type"] = "checkbox"
options["value"] = @checked_value
options["checked"] = "checked" if input_checked?(object, options)
if options["multiple"]
add_default_name_and_id_for_value(@checked_value, options)
options.delete("multiple")
else
add_default_name_and_id(options)
end
include_hidden = options.delete("include_hidden") { true }
checkbox = tag("input", options)
if include_hidden
hidden = hidden_field_for_checkbox(options)
hidden + checkbox
else
checkbox
end
end
private
def checked?(value)
case value
when TrueClass, FalseClass
value == !!@checked_value
when NilClass
false
when String
value == @checked_value
else
if value.respond_to?(:include?)
value.include?(@checked_value)
else
value.to_i == @checked_value.to_i
end
end
end
def hidden_field_for_checkbox(options)
@unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe
end
end
end
end
end
| true |
ef0591509b832cc1095e5885014bfb4565db4fd6 | Ruby | LongTran415/phase-0-tracks | /ruby/santa.rb | UTF-8 | 3,380 | 3.828125 | 4 | [] | no_license |
class Santa
attr_reader :name, :ice_cream
attr_accessor :name, :ice_cream
def initialize (gender, ethnicity, hair_color, age, ice_cream, name)
puts "Initializing Santa instance ..."
@gender = gender
@ethnicity = ethnicity
@hair_color = hair_color
@age = age
@ice_cream = ice_cream
@name = name
@greeting = "Says Ho, ho, ho! Happy holidays!"
end
def reindeer_sorter(rank)
@reindeer_rank = rank
rank = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
puts "These are my favorite reindeer starting with my favorite:"
rank.map do |index|
puts "#{index}"
end
end
def age(integer)
integer += 0
puts "Age: #{integer}"
end
def speak
@greeting = "Says Ho, ho, ho! Happy holidays!"
end
def eat_milk_and_cookies(cookie_type)
puts "That was a good #{cookie_type} cookie!"
end
def about
puts "Name: #{@name}"
puts "Gender: #{@gender}"
puts "Ethnicity: #{@ethnicity}"
puts "Ice Cream pref: #{@ice_cream}"
puts "Age: #{@age}"
puts "Hair color: #{@hair_color}"
puts "#{@greeting}"
puts ""
end
#>>> getter methods make code readable
# def name
# @name
# end
# def ice_cream
# @ice_cream
# end
#>>> setter method makes code writable
# def name=(new_name)
# @name = new_name
# end
# def ice_cream=(ice_cream_flavor)
# @ice_cream = ice_cream_flavor
# end
end
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# santa program algorithm
# create an array and add wanted instances
# loop through array and call methods on each one randomly
# set age range from 1..140
# loop the program to test 1000 santas
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# driver code for initializing santas
santa = Santa.new("male", "Unicorn", "blue", 22, "Orange cream", "Zoro")
santa.name = "Zoro"
santa.age(22)
santa.about
santa.speak
santa.eat_milk_and_cookies("chocolate chip")
santa.reindeer_sorter(["Rudolph", "Dasher", "Dancer", "Prancer", "Comet", "Vixen", "Cupid", "Donner", "Blitzen"])
santa = Santa.new("male", "Merman", "Green", 21, "Banana nut", "Luffy")
santa.name = "Luffy"
santa.age(21)
santa.ice_cream = "Chocolate"
santa.about
santa.speak
santa.eat_milk_and_cookies("chocolate, chocolate chip")
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# utilizing arrays for initializing santas
santas = []
example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"]
example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"]
example_hair_color = ["Blue", "Green", "Brown", "Rainbow", "Violet", "Red", "N/A"]
example_ice_cream = ["Vanilla", "Caramel", "Strawberry", "Neapolitan", "", "Chocolate", "N/A"]
example_names = ["Charlie", "Kim", "Rupert", "Mehul", "", "Lisa", "Bart"]
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# looping through the program, calling methods on
# each instance.
example_age = rand(0..140)
index = 0
while index < 1000
example_genders.length.times do |i|
santas << santa = Santa.new(example_genders.sample,
example_ethnicities.sample,
example_hair_color.sample, example_age,
example_ice_cream.sample,
example_names.sample).about
santas.each {|age| example_age = rand(0..140)}
index += 1
end
end
| true |
b6a34d5cf6974d7f7e53333b9bf7eaa8c086ca87 | Ruby | portugol/decode | /Algoritmos Traduzidos/Ruby/Algoritmos_Filipe_Farinha/01.rb | UTF-8 | 109 | 3 | 3 | [] | no_license | #programa que imprime um triangulo no ecra
for i in 1..5
for j in 1..i
print "*"
end
print "\n"
end | true |
7b97c3a74be54a48f0a7a60b55d696604986b651 | Ruby | iheartkode/LearningRubyCode | /Hashes.rb | UTF-8 | 699 | 3.875 | 4 | [] | no_license | # Practicing hashes, temporary solution storing key, values.
# Mark Howard 07/17/2014
#Learning Ruby
# Method that does the work.
def insert_record
# Empty hash to store passwords in.
passwords = {}
# Loop to keep asking for sites and passwords.
while true
# Ask user for info.
puts "Enter the site name."
site = gets.chomp
puts "Enter the password."
pass = gets.chomp
# Inserts the users site and password into the hash.
passwords[site] = pass
# List out the sites and passwords,
puts "Listing passwords..."
sleep 1
passwords.each do |site, password|
puts "Site: #{site} \n Password: #{password}"
end
end
end
insert_record()
| true |
09fd3bc6f8907a50d2e8a7cd030feacf02068c59 | Ruby | redfolgersGA/code_gym | /u3/d04/rails/u3_skully_rulez/config/routes.rb | UTF-8 | 1,864 | 2.875 | 3 | [] | no_license | Rails.application.routes.draw do
# root to: is like doing app.get("/") in Javascript
root to: "articles#index"
# we can do everything down there with JUST ONE, yes one! line of code
# this is an expression not a method that creates these routes
# :article :dogs are symbols and the only: is a hash
resources :article, only: [:index, :show]
# resources :users, except: [:destroy, :update]
end
# a ruby has is a collection of data that is a key value pair
# { :key => "value"} is the equivalent to this:
# { key: "value" }
# first resource called articles
# get "/articles", to: "articles#index"
# get "/articles/:id", to: "articles#show"
# post "/articles", to: "articles#create"
# put "/articles/:id", to: "articles#update"
# delete "/articles/:id", to: "articles#destroy"
# get "/articles/new", to: "articles#new"
# get "articles/:id/edit", to: "articles#edit"
# end
# the one we care about here is line 2 it is the function that is
# associated with that route. it is the method that handles this request
# in ruby there are no functions heres the route were gonna send that request to articles/index
#controller is a class that hold the methods for a particular resource
# app/controllers/articles_controller.rb is created on the commandline with rails g controller articles
# convention over configuration
# in our articles.controller we need to make a def index method
# this is the second resource
# get "/users", to: "users#index"
# get "/users/:id", to: "users#show"
# post "/users", to: "users#create"
# put "/users/:id", to: "users#update"
# delete "/users/:id", to: "users#destroy"
# get "/users/new", to: "users#new"
# get "users/:id/edit", to: "users#edit"
# end
# Command line interface CHEAT SHEET
# [rails]CLI tool
# rails now <project name>
# rails generate controller <controller name>
# rails g...
# rails server
# rails routes
| true |
130cd61d0a35873bf640ab2546562e5ccc633bc9 | Ruby | hone/parallel_specs | /lib/parallel_tests.rb | UTF-8 | 3,235 | 2.734375 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | require 'parallel'
class ParallelTests
# parallel:spec[2,controller] <-> parallel:spec[controller]
def self.parse_test_args(args)
num_processes = Parallel.processor_count
if args[:count].to_s =~ /^\d*$/ # number or empty
num_processes = args[:count] unless args[:count].to_s.empty?
prefix = args[:path_prefix]
else # something stringy
prefix = args[:count]
end
[num_processes.to_i, prefix.to_s]
end
# finds all tests and partitions them into groups
def self.tests_in_groups(root, num)
tests_with_sizes = slow_specs_first(find_tests_with_sizes(root))
groups = []
current_group = current_size = 0
tests_with_sizes.each do |test, size|
# inserts into next group if current is full and we are not in the last group
if (0.5*size + current_size) > group_size(tests_with_sizes, num) and num > current_group + 1
current_size = size
current_group += 1
else
current_size += size
end
groups[current_group] ||= []
groups[current_group] << test
end
groups.compact
end
def self.run_tests(test_files, process_number)
require_list = test_files.map { |filename| "\"#{filename}\"" }.join(",")
cmd = "export RAILS_ENV=test ; export TEST_ENV_NUMBER=#{test_env_number(process_number)} ; ruby -Itest -e '[#{require_list}].each {|f| require f }'"
execute_command(cmd)
end
def self.execute_command(cmd)
f = open("|#{cmd}", 'r')
all = ''
while char = f.getc
char = (char.is_a?(Fixnum) ? char.chr : char) # 1.8 <-> 1.9
all << char
print char
STDOUT.flush
end
all
end
def self.find_results(test_output)
test_output.split("\n").map {|line|
line = line.gsub(/\.|F|\*/,'')
next unless line_is_result?(line)
line
}.compact
end
def self.failed?(results)
return true if results.empty?
!! results.detect{|line| line_is_failure?(line)}
end
def self.test_env_number(process_number)
process_number == 0 ? '' : process_number + 1
end
protected
def self.slow_specs_first(tests)
tests.sort_by{|test, size| size }.reverse
end
def self.line_is_result?(line)
line =~ /\d+ failure/
end
def self.line_is_failure?(line)
line =~ /(\d{2,}|[1-9]) (failure|error)/
end
def self.group_size(tests_with_sizes, num_groups)
total_size = tests_with_sizes.inject(0) { |sum, test| sum += test[1] }
total_size / num_groups.to_f
end
def self.find_tests_with_sizes(root)
tests = find_tests(root).sort
#TODO get the real root, atm this only works for complete runs when root point to e.g. real_root/spec
runtime_file = File.join(root,'..','tmp','parallel_profile.log')
lines = File.read(runtime_file).split("\n") rescue []
if lines.size * 1.5 > tests.size
# use recorded test runtime if we got enough data
times = Hash.new(1)
lines.each do |line|
test, time = line.split(":")
times[test] = time.to_f
end
tests.map { |test| [ test, times[test] ] }
else
# use file sizes
tests.map { |test| [ test, File.stat(test).size ] }
end
end
def self.find_tests(root)
Dir["#{root}**/**/*_test.rb"]
end
end | true |
71e333b5ee34324e2f6441dc9bc6c8ce4ffdc900 | Ruby | Jbern16/trend_font | /app/services/google_font_service.rb | UTF-8 | 614 | 2.640625 | 3 | [] | no_license | class GoogleFontService
def initialize
@connection = Faraday.new(url: "https://www.googleapis.com")
end
def get_fonts(sort_param)
@connection.get do |req|
req.url '/webfonts/v1/webfonts'
req.params['key'] = ENV['GOOGLE_FONT_KEY']
req.params['sort'] = sort_param
end
end
def trending_fonts
parse(get_fonts('trending'))
end
def popular_fonts
parse(get_fonts('popularity'))
end
def recent_fonts
parse(get_fonts('date'))
end
private
def parse(response)
parsed = JSON.parse(response.body, symbolize_names: true)
parsed[:items]
end
end
| true |
29f7264afe49c92adf39284c4ed79a55e26dfcaf | Ruby | ben-amor/hangman | /lib/game_status_calculator.rb | UTF-8 | 310 | 2.921875 | 3 | [] | no_license |
class GameStatusCalculator
def calculate_game_status(game_state)
case
when game_state.lives_remaining == 0
GameState::LOST
when (game_state.current_word.chars - game_state.characters_guessed).empty?
GameState::WON
else
GameState::IN_PROGRESS
end
end
end | true |
d0f31474ce856d35a5e5f204bb4faf0c24e4619b | Ruby | jonathongardner/slots-jwt | /test/dummy/test/models/generic_user_test.rb | UTF-8 | 4,289 | 2.53125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'slots_test'
class GenericUserTest < SlotsTest
test "should find user for authentication" do
user = generic_users(:some_great_generic_user)
assert_equal user, GenericUser.find_for_authentication(user.email), 'Should find_for_authentication user with correct email'
assert_empty_user GenericUser.find_for_authentication('notemail@somweher.com'), 'Should not find_for_authentication user with wrong email'
assert_empty_user GenericUser.find_for_authentication(''), 'Should not find_for_authentication user that doesnt exist'
assert_empty_user GenericUser.find_for_authentication(nil), 'Should not find_for_authentication user that doesnt exist'
end
test "should find_for_authentication user using config" do
Slots::JWT.configure do |config|
config.logins = {email: /@/, username: //} # Most inclusive should be last
end
great_user = generic_users(:some_great_generic_user)
assert_equal great_user, GenericUser.find_for_authentication(great_user.email), 'Should find_for_authentication great user with email'
assert_equal great_user, GenericUser.find_for_authentication(great_user.username), 'Should find_for_authentication great user with username'
bad_user = generic_users(:some_bad_generic_user)
assert_equal bad_user, GenericUser.find_for_authentication(bad_user.email), 'Should find_for_authentication bad user with email'
assert_empty_user GenericUser.find_for_authentication(bad_user.username), 'Should not find_for_authentication bad user with username because it matches email regex'
end
test "should not authenticate if password blank" do
great_user = generic_users(:some_great_generic_user)
assert_singleton_method(great_user, :authenticate, count: 0) do
assert_not great_user.authenticate?(nil), 'Should not authenticate nil password'
assert_not great_user.authenticate?(''), 'Should not authenticate blank password'
end
assert_singleton_method(great_user, :authenticate, to_return: true) do
assert great_user.authenticate?('test'), 'Should authenticate none blank password'
end
end
test "should not authenticate user if not persisted" do
assert_not GenericUser.new.authenticate?('test'), 'Should not authenticate if not saved'
great_user = generic_users(:some_great_generic_user)
assert_singleton_method(great_user, :persisted?, to_return: false) do
assert_not great_user.authenticate?(GenericUser.pass), 'Should not authenticate if not persisted'
end
assert great_user.authenticate?(GenericUser.pass), 'Should authenticate user with valid passowrd'
end
test "should not authenticate user unless allowed_new_token?" do
bad_user = generic_users(:some_bad_generic_user)
assert_singleton_method(bad_user, :authenticate, to_return: true) do
assert_not bad_user.authenticate?(GenericUser.pass), 'Should not authenticate if reject_new_token'
end
great_user = generic_users(:some_great_generic_user)
assert_singleton_method(great_user, :allowed_new_token?, to_return: false) do
assert_not great_user.authenticate?(GenericUser.pass), 'Should not authenticate if not allowed_new_token?'
end
assert great_user.authenticate?(GenericUser.pass), 'Should authenticate user with valid passowrd'
end
test "should authenticate user" do
great_user = generic_users(:some_great_generic_user)
assert great_user.authenticate?(GenericUser.pass), 'Should authenticate user with valid passowrd'
assert_not great_user.authenticate?(GenericUser.pass + '_a_little_sometin_sometin'), 'Should not authenticate user with invalid password'
end
test "should authenticate user BANG" do
great_user = generic_users(:some_great_generic_user)
assert_singleton_method(great_user, :authenticate?, to_return: true, count: 1) do
assert great_user.authenticate!('test'), 'Should authenticate user with valid password'
end
assert_singleton_method(great_user, :authenticate?, to_return: false, count: 1) do
assert_raises(Slots::JWT::AuthenticationFailed) do
great_user.authenticate!(GenericUser.pass)
end
end
end
def assert_empty_user(user, message)
# need to return empty user for authenticate!
assert user.new_record?, message
end
end
| true |
1dc8595421f454aa7b05cc393108f8a4d34914c9 | Ruby | grzegorzl1/przerwa_tygodniowa | /samogloski.rb | UTF-8 | 99 | 3.5625 | 4 | [] | no_license | def vowel_count(string)
string.count'aeiouy'
end
vow = vowel_count("baaaak, baaoiuyr")
puts vow
| true |
55818faeadd7f62394d5158b8de3b0dc72e7a6ff | Ruby | CepCap/intern | /work/redefarr/redefarr.rb | UTF-8 | 1,758 | 3.78125 | 4 | [] | no_license | class MyArray
attr_accessor :init_arr
def initialize(init_array)
@init_arr = init_array
end
def my_length
init_arr.each do |el|
@count = 0 unless @count
@count += 1
end
@count
end
def my_count(value)
counting = 0
init_arr.each do |el|
counting += 1 if el == value
end
counting
end
def my_find(value)
init_arr.each.with_index { |el, index| return index if el == value }
nil
end
def my_map_find(value)
init_arr.map.with_index { |el, index| index if el == value }.compact
end
def my_max
current_max = init_arr[0]
init_arr.each { |el| current_max = el if el > current_max }
current_max
end
def my_select
selected = []
init_arr.each { |el| selected << el if el % 2 == 0 }
selected
end
def my_reverse
reverse = []
init_arr.each { |el| reverse.unshift(el) }
reverse
end
def my_flatten
init_arr.each.with_index do |el, index|
if el.is_a? Array
init_arr.delete_at(index)
flat(el, index)
end
end
end
def flat(array, index)
array.each.with_index do |el, inner_index|
init_arr.insert(index + inner_index, el)
end
end
def try_all
puts 'My length-------'
p self.my_length
puts 'My count--------'
p self.my_count(40)
puts 'My find (finding 50)-----'
p self.my_find(50)
puts 'My max------'
p self.my_max
puts 'My select-----'
p self.my_select
puts 'My reverse-----'
p self.my_reverse
puts 'My flatten-----'
p self.my_flatten
end
end
arr1 = MyArray.new([25, 7, 80 ,40])
arr2 = MyArray.new((1..100).to_a)
arr1.try_all
arr2.try_all
arr3 = MyArray.new([1,[1,2,3,[1,2,3,4]],3,4,5,6])
puts 'Flatten'
p arr3.my_flatten
| true |
3d00286b83a24c3740e43ddc4a68519f64cf6e01 | Ruby | rhivent/ruby_code_N_book | /book-of-ruby/ch17/threads1.rb | UTF-8 | 514 | 3.75 | 4 | [] | no_license | # The Book of Ruby - http://www.sapphiresteel.com
# This is a simple threading example which, however,
# doesn't work as anticipated!
words = ["hello", "world", "goodbye", "mars" ]
numbers = [1,2,3,4,5,6,7,8,9,10]
startTime = Time.new
puts( "Start: %10.9f" % startTime )
Thread.new{
words.each{ |word| puts( word ) }
}
Thread.new{
numbers.each{ |number| puts( number ) }
}
endTime = Time.new
puts( "End: %10.9f" % endTime.to_f )
totalTime = endTime-startTime
puts( "Total Time: %10.9f" % totalTime.to_f ) | true |
dedda01f7c99e11fe1fbdea825307da113849b32 | Ruby | posgarou/whatsfordinner | /server/lib/extensions/float.rb | UTF-8 | 177 | 3.015625 | 3 | [] | no_license | class Float
# E.g., 2.5 => 2.5 and 1.0 => 1
#
# From the venerable Yehuda Katz: http://stackoverflow.com/a/1077648
def prettify
to_i == self ? to_i : self
end
end
| true |
e7f64b912a0a61ed2aef0446bc39c4cb4c16f0c6 | Ruby | helenaalinder/baxapplikation | /app/models/product.rb | UTF-8 | 562 | 2.59375 | 3 | [] | no_license | class Product < ApplicationRecord
validates :name, presence: true
has_many :purchases
has_many :orders, through: :order_items
has_many :order_items, inverse_of: :product
def product_price
if (OrderItem.where(product: self).sum(:quantity) > 0)
OrderItem.where(product: self).sum(:price) / OrderItem.where(product: self).sum(:quantity)
else
0
end
end
def set_price
@price = self.product_price
update_attribute(:price, @price)
end
def total_quantity
OrderItem.where(product: self).sum(:quantity)
end
end
| true |
6cebab5e5e06efa8cccd28ee2a7c14bd13215555 | Ruby | sh1okoh/competitive_prog | /ABC/ABC166/problemA.rb | UTF-8 | 98 | 3.265625 | 3 | [] | no_license | def solve
s = gets.chomp
if s == 'ABC'
print 'ARC'
else
print 'ABC'
end
end
solve
| true |
6d12d46c52069261dd5c1069083e72fe9cc62774 | Ruby | Pwako11/operators-online-web-prework | /lib/operations.rb | UTF-8 | 476 | 3.03125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def unsafe?(speed)
#if speed is greater than 60
if Speed % > 60
returns "true" (FAILED - 1)
end
#if speed is less than 60
if Speed % < 40
returns "true"
end
if Speed % >=40 or <= 60
Returns "false"
end
end
Def not_safe?(speed)
#if speed is greater than 60
Speed = 60
Speed > 59 ? "true" : "False"
#if speed is less than 60
Speed = 40
Speed < 39 ? "true : "False"
#if speed is between
Speed >=40 or <= 60
Returns "false" | true |
cbe4ebaeda8be1e40bbf0b05e0176d1bbf00fa47 | Ruby | pombredanne/ruby-sslyze | /lib/sslyze/certificate/extensions/x509v3_basic_constraints.rb | UTF-8 | 1,328 | 2.75 | 3 | [
"MIT"
] | permissive | require 'sslyze/certificate/extensions/extension'
module SSLyze
class Certificate
class Extensions
#
# Represents the `<X509v3BasicConstraints>` XML element.
#
class X509v3BasicConstraints < Extension
#
# Specifies whether the `critical` constraint was specified.
#
# @return [Boolean]
#
def critical?
@node.inner_text.include?('critical')
end
#
# The value of the `CA` constraint.
#
# @return [Boolean, nil]
#
def ca?
if @node.inner_text.include?('CA:TRUE') then true
elsif @node.inner_text.include?('CA:FALSE') then false
end
end
#
# The value of the `pathlen` constraint.
#
# @return [Integer, nil]
#
def path_length
@path_length ||= if (match = @node.inner_text.match(/pathlen:(\d+)/))
match[1].to_i
end
end
alias path_len path_length
#
# The raw basic constraint String.
#
# @return [String]
#
def to_s
if @node then @node.inner_text
else ''
end
end
alias to_str to_s
end
end
end
end
| true |
825bfc9ed5fd4c5c45b40c0e5bc74cc4e373877e | Ruby | Sammyfrw/Metis-Bootcamp | /Week-6/Week 6 Friday Notes.rb | UTF-8 | 1,657 | 3.140625 | 3 | [] | no_license | # # Rack is used by Rails, Sinatra, etc, it is also used in many gems such as Monban, authentication based gems and documentation, etc.
# # What does it do? It handles incoming HTTP requests.
# HTTP: Asks a server to return resource(GET), create(POST) or others (PATCH,PUT, DELETE, etc).
# Requests are sent to URL. We get a status code in response.
# Headers contain metadata such as content type, caching rules, etc.
# Body contains the requested resource. Chrome has several devtools to look at these things.
# Each framework (Rails, Sinatra, custom frameworks) has to interact with many
# different kinds of servers running different things. For each framework, it
# needs to be able to work with it. This creates a jumbled mess. Rack handles
# it for us!
# Rack is a great model for HTTP request/response model. The official rack
# spec is a ruby object that responds to call, takes exactly one arg - the
# env, and it returns an array of 3 values: status, headers, and body. It must
# respond to each.
# The env is a hash containing a lot of information about the request and who
# made the request. It's a lot, but while it may be a lot on its own, Rack's
# strength comes in when Rack apps are chained together to enforce its
# position as middleware.
# Dependency injections can be used to not hardcore things, passing names as
# an argument. That way, very little things need to be a dependency that is
# hardcoded. With middleware, each app gets a chance to change the env
# argument passed in before it moves up into the next app in the chain,
# changing status, headers and body before it returns.
| true |
235c68b5b68867d8f860d1138ff87f289c73f628 | Ruby | verg/forecast | /lib/forecast.rb | UTF-8 | 1,625 | 3.1875 | 3 | [] | no_license | require_relative 'forecast/forecast_client'
require_relative 'forecast/forecast_result'
require_relative 'forecast/minutely_result'
require_relative 'forecast/location'
require_relative 'forecast/time_range'
require 'yaml'
module Forecast
class Forecast
CONFIG = YAML.load_file('config.yml')
Lat = CONFIG['latitude']
Lng = CONFIG['longitude']
attr_reader :location, :current_temp, :minutely_summary, :hourly_summary,
:prob_rain_next_hour, :minutely_results
def initialize(location = nil)
@location = location || Location.new({latitude: Lat, longitude: Lng})
end
def get(client = Client.new)
result = client.fetch(location)
@current_temp = result.current_temp
@minutely_summary = result.minutely_summary
@hourly_summary = result.hourly_summary
@prob_rain_next_hour = result.prob_rain_next_hour
@minutely_results = result.minutely_results
end
def rain_next_hour?
prob_rain_next_hour >= 0.1
end
def summary
puts "#{minutely_summary} #{hourly_summary}"
puts "Currently #{current_temp.round}F / #{current_temp_celc.round}C."
if rain_next_hour?
puts "Ten mins with least rain during next hour: #{print_ten_min_window}."
end
end
def lowest_precip_intensity_next_hour(mins)
minutely_results.least_precip_range(mins)
end
private
def print_ten_min_window
lowest_precip_intensity_next_hour(10).readable_string
end
def current_temp_celc
far_to_cel(current_temp)
end
def far_to_cel(far)
(far - 32) * 5 / 9
end
end
end
| true |
249522a412160fb78419b7419af231d744786cb4 | Ruby | hdgarrood/tank-game | /lib/tankgame/game_objects/barrel.rb | UTF-8 | 1,729 | 2.890625 | 3 | [] | no_license | require 'tankgame/geometry/angle'
module TankGame
module GameObjects
# to be included in Player
module Barrel
include Geometry
def initialize_barrel
@barrel_angle = Angle.new(0)
@barrel_sprite = {
:left => Resources.sprites[:barrel_left],
:right => Resources.sprites[:barrel_right]
}
end
def barrel_rotate_speed
0.1
end
def handle_barrel_events
# work out which direction the barrel wants to be pointing
mouse_angle = Angle.bearing(centre, Mouse)
case mouse_angle.quadrant
when :first
@barrel_target = Angle.new(0)
when :second
@barrel_target = Angle.new(Math::PI)
else
@barrel_target = mouse_angle
end
end
def do_barrel_logic
@barrel_angle = new_barrel_angle(@barrel_angle, @barrel_target)
end
def draw_barrel
@barrel_sprite[@barrel_angle.direction].draw_rot(
*centre, 0, @barrel_angle.to_gosu, 0)
end
# returns the new angle which the barrel should be pointing, given its
# current angle and its target
def new_barrel_angle(current, target)
hard_left = Angle.new(Math::PI)
hard_right = Angle.new(0)
if (current.to_f - target.to_f).abs <= barrel_rotate_speed
target
elsif target == hard_left || current == hard_right
current - barrel_rotate_speed
elsif target == hard_right || current == hard_left
current + barrel_rotate_speed
elsif current < target
current + barrel_rotate_speed
else
current - barrel_rotate_speed
end
end
end
end
end
| true |
b7d4f2b0a5910c68307f698fcc31c1fda466e6ea | Ruby | jralorro93/emoticon-translator-prework | /lib/translator.rb | UTF-8 | 812 | 3.515625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "yaml"
require 'pry'
def load_library(path)
emoticons = YAML.load_file(path)
new_hash = {}
emoticons.each do |emotion, array|
new_hash["get_meaning"] ||= {}
new_hash["get_emoticon"] ||= {}
new_hash["get_meaning"][array.last] ||= emotion
new_hash["get_emoticon"][array.first] ||= array.last
end
new_hash
end
def get_japanese_emoticon(path, emoticon)
lib_hash = load_library(path)
dictionary = lib_hash['get_emoticon']
if dictionary.has_key?(emoticon)
dictionary[emoticon]
else
"Sorry, that emoticon was not found"
end
end
def get_english_meaning(path, emoticon)
lib_hash = load_library(path)
dictionary = lib_hash['get_meaning']
if dictionary.has_key?(emoticon)
dictionary[emoticon]
else
"Sorry, that emoticon was not found"
end
end | true |
9b95298577e87c52eadc8648d3ba07d0e2f1dc3b | Ruby | quetzalsa/sample_app3 | /example_user.rb | UTF-8 | 379 | 3.25 | 3 | [] | no_license | class User
attr_accessor :firstn, :lastn, :email
def initialize(attributes = {})
@firstn = attributes[:firstn]
@lastn = attributes[:lastn]
@email = attributes[:email]
end
def full_name
puts @firstn + " " + @lastn + @email
end
def formatted_email
full_name(@firstn, @lastn)
end
def alphabetical_name
"#{@firstn}, #{@lastn}"
end
end
| true |
a734c7072e16347b020a0f45f4b7e6f45a155b04 | Ruby | LALOPSB/Exercise-PrimeFactors-Ruby | /lib/primeFactorsCalculator.rb | UTF-8 | 310 | 3.515625 | 4 | [] | no_license | class PrimeFactorsCalculator
def calculate_prime_factors (number)
prime_array = []
p = 2
if number < 2
return prime_array
end
while p <= number
if number % p == 0
prime_array.push(p)
number/=p
end
p +=1
end
return prime_array
end
end
| true |
30e36bcedbd3e0d36cc5f05dda994cce5df303ac | Ruby | olliefw/nbody | /Planets.rb | UTF-8 | 1,286 | 3.234375 | 3 | [] | no_license | require "gosu"
class Planets
attr_reader :x_pos, :y_pos, :x_vel, :y_vel, :mass, :force_x, :force_y
def initialize (x_pos, y_pos, x_vel, y_vel, mass, planet_image, sizeu)
@x_pos = x_pos
@y_pos = y_pos
@x_vel = x_vel
@y_vel = y_vel
@mass = mass
@planet_image = planet_image
@force_x = 0
@force_y = 0
@G = 6.674e-11
@sizeu = sizeu
end
def forcex(x, y, mass)
force = (@G * @mass * mass)/((@x_pos - x)**2 + (@y_pos - y)**2)
@force_x -= force * (@x_pos - x)/ (Math.sqrt((@x_pos - x)**2 + (@y_pos - y)**2))
end
def forcey(x, y, mass)
force = (@G * @mass * mass)/((@x_pos - x)**2 + (@y_pos - y)**2)
@force_y -= force * (@x_pos - y) / (Math.sqrt((@y_pos - y)**2 + (@y_pos - y)**2))
puts @force_y
end
def accx
acc = @mass / @force_x
@x_vel += acc * 25000
@x_pos += @x_vel * 25000
end
def accy
acc = @mass / @force_y
@y_vel += acc * 25000
@y_pos += @y_vel * 25000
end
def backto0
@force_x = 0
@force_y = 0
end
def draw
#puts @planet_image
#puts(@x_pos / @sizeu)*320 + 640/2 - @planet_image.width / 2
@planet_image.draw((@x_pos / @sizeu)*320 + 640/2 - @planet_image.width / 2,(@y_pos / @sizeu)*320 + 640 / 2 - @planet_image.height / 2, 1 )
end
end
| true |
b6ab5f757e267d68eb3c81c7299b5ddd0441137d | Ruby | eddpeterson/RSpecDemo | /implicit_spec.rb | UTF-8 | 446 | 2.671875 | 3 | [] | no_license | describe 42 do
it { should be_even }
it { should_not be_zero }
end
describe Array do
it { should be_empty }
it { should have(0).items }
end
describe [1, 2, 3, 3] do
its(:size) { should == 4 }
its("uniq.size") { should == 3 }
end
# Explicit subject
describe "An array containint 1, 2, 3, 3" do
subject { [1, 2, 3, 3] }
its(:size) { should == 4 }
end
describe Array do
it "is empty" do
subject.should be_empty
end
end
| true |
cfbf846b1b1dc8ca5b8b99a764dd13a40e2d2bff | Ruby | briant1/world-time-too | /app/services/country_service.rb | UTF-8 | 1,019 | 2.75 | 3 | [] | no_license | require 'wikipedia'
class CountryService
def initialize
end
def get_or_create_country(data)
country = Country.find_by_name(data[:country_code])
if !country
wikipedia_url = Wikipedia.find(data[:country_code]).fullurl
country = Country.create(name: data[:country_code], wikipedia_url: wikipedia_url)
end
country
end
def get_or_create_city(country, data)
city = City.where(city: data[:city], state: data[:state]).first
if !city
timezone = Timezone.lookup(data[:lat], data[:lng])
wikipedia_page = Wikipedia.find("#{data[:city]} #{data[:state]}")
city = City.create(city: data[:city],
state: data[:state],
wikipedia_url: wikipedia_page.fullurl,
timezone: timezone,
has_dst: timezone.dst?(Time.now),
country_id: country.id,
lng: data[:lng],
lat: data[:lat])
end
city
end
end
| true |
5f98a15ec361f85416c3014d23a15ed380ed7ffb | Ruby | hnpbqy/LAB | /ruby/practic/1/helloworld.rb | UTF-8 | 68 | 2.53125 | 3 | [] | no_license | # Ruby Sample program from www.sapphiresteel.com
puts 'Hello world' | true |
a79e46c2a40f4309117c886d3e942aa8e99a600d | Ruby | synmal/wallet | /app/models/debit.rb | UTF-8 | 643 | 2.515625 | 3 | [] | no_license | class Debit < WalletTransaction
validate :only_from_debiter_wallet, :sufficient_balance
before_validation :debit_to_owner
after_create :deduct_from_wallet
private
def only_from_debiter_wallet
debiter = transact_to
unless transact_from.is_a?(Wallet) && transact_from.owner.id == debiter.id
errors.add(:transact_from, 'Can only debit to correct owner')
end
end
def debit_to_owner
self.transact_from = transact_to.wallet
end
def deduct_from_wallet
Debit.transaction do
wallet = transact_from.lock!
self.track_changes
wallet.balance -= amount
wallet.save!
end
end
end | true |
02b3b820e2a54517dfc14ba8f99f05dfb6284896 | Ruby | jimivyas/learn_ruby | /08_timer/timer.rb | UTF-8 | 808 | 3.3125 | 3 | [] | no_license | class Timer
attr_accessor :seconds
def initialize(seconds=0)
@seconds = seconds
end
def time_string
hours = (@seconds / (60 * 60)).to_i
minutes = ((@seconds - hours * 60 * 60) / 60).to_i
seconds = (@seconds - hours * 60 * 60 - minutes * 60)
'%02d:%02d:%02d' % [hours, minutes, seconds]
end
def padded(seconds)
case seconds
when 0
@time = "00"
when 1..9
@time = "0" + seconds.to_s
else
@time = seconds.to_s
end
end
end
# def seconds=(num)
# @time_string = 0
# @time_string=(num)
# end
# def time_string=(num)
# hours = padded(num / 3600)
# minutes = padded((num%3600) / 60)
# num = num % 60
# seconds = padded ((num%3600)%60)
# @time_string = "#{hours}" + ":" + "#{minutes}" + ":" + "#{seconds}"
# return @time_string
# end
| true |
78732acc3dc4a0702fea2c45b2ed46673b20ab23 | Ruby | hatsu38/atcoder-ruby | /abc303/b.rb | UTF-8 | 1,632 | 3.515625 | 4 | [] | no_license | # frozen_string_literal: true
### 例
# 1,2,…,N と番号づけられた
# N 人が
# M 回、一列に並んで集合写真を撮りました。
# i 番目の撮影で左から
# j 番目に並んだ人の番号は
# a
# i,j
#
# です。
# ある二人組は
# M 回の撮影で一度も連続して並ばなかった場合、不仲である可能性があります。
# 不仲である可能性がある二人組の個数を求めてください。なお、人
# x と人
# y からなる二人組と人
# y と人
# x からなる二人組は区別しません。
# input
# RNBQKBNR
# output
# Yes
# 長さ
# 8 の文字列
# S が与えられます。
# S には K, Q がちょうど
# 1 文字ずつ、R, B, N がちょうど
# 2 文字ずつ含まれます。
# S が以下の条件を全て満たしているか判定してください。
# S において左から
# x,y (x<y) 文字目が B であるとする。このとき
# x と
# y の偶奇が異なる。
# K は
# 2 つの R の間にある。より形式的には、
# S において左から
# x,y (x<y) 文字目が R であり、
# z 文字目が K であるとする。このとき、
# x<z<y が成り立つ。
# 例
# 4 2
# 1 2 3 4
# 4 3 1 2
# output
# 2
# 上記の判定をするプログラムを作成してください。
N, M = gets.split.map(&:to_i)
grid = Array.new(M) { gets.chomp.split.map(&:to_i) }
hash = Hash.new(0)
[*1..N].combination(2).to_a.each do |a, b|
hash[[a, b].sort] = false
end
grid.each_with_index do |g, _i|
g.each_cons(2) do |a, b|
hash[[a, b].sort] = true
end
end
puts(hash.values.count(&:!))
| true |
5e4d6d872c50bef437d1a6b3507579c1b22f5139 | Ruby | mihaibaboi/tournaments | /app.rb | UTF-8 | 7,841 | 2.515625 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader' if development?
require 'json'
require 'data_mapper'
require File.dirname(__FILE__) + '/models/model.rb'
STATUS_SUCCESS = 'success'
STATUS_FAILED = 'failed'
STATUS_CREATED = 'created'
before do
if request.post? || request.put?
request.body.rewind
@request_payload = JSON.parse request.body.read
end
end
show_users = lambda do
users = User.all
users.to_json
end
find_by_username = lambda do
users = User.all(:username.like => "%#{params[:username]}%")
users.to_json
end
show_user_detail = lambda do
user = User.get(params[:id])
user.to_json
end
create_user = lambda do
user = User.new
user.username = @request_payload['username']
user.first_name = @request_payload['first_name'] if @request_payload.has_key?('first_name')
user.last_name = @request_payload['last_name'] if @request_payload.has_key?('last_name')
result = process_save(user)
result.to_json
end
add_players_in_tournament = lambda do
tournament = Tournament.get(@request_payload['tournament_id'])
users = @request_payload['users']
users.each do |user_id|
if Player.unique?(params[:id], user_id)
user = User.get(user_id)
tournament.users << user
end
end
if tournament.save
status 201
resource = { :tournament => tournament, :players => tournament.users }
result = { :status => STATUS_CREATED, :resource => resource }
else
status 500
result = { :status => STATUS_FAILED, :message => tournament.errors.to_hash }
end
result.to_json
end
show_players_in_tournament = lambda do
tournament = Tournament.get(params[:id])
resource = { :tournament => tournament, :players => tournament.users }
resource.to_json
end
show_matches_in_tournament = lambda do
tournament = Tournament.get(params[:id])
resource = get_tournament_scores(tournament)
resource.to_json
end
log_match_in_tournament = lambda do
tournament = Tournament.get(@request_payload['tournament_id'])
if tournament.players.empty?
return { :status => 'error', :message => 'Tournament has no players' }
end
unless @request_payload.has_key?('scores')
status 400
return { :status => 'error', :message => 'Payload should contain the :scores key' }
end
match = Match.new
if @request_payload['scheduled_at']
match.scheduled_at = @request_payload['scheduled_at']
end
scores = @request_payload['scores']
sorted = scores.sort_by { | score_hashes | score_hashes['games_won'] }
points = 0
users = []
sorted.each do | result |
users << result['user_id']
score = Score.new
score.user_id = result['user_id']
score.games_won = result['games_won']
score.points = points
points += 1
match.scores << score
end
if validate_match(tournament, users)
tournament.matches << match
if tournament.save
status 201
result = get_tournament_scores(tournament)
else
status 400
result = { :status => 'error', :message => tournament.errors.to_hash }
end
else
status 400
result = { :status => 'error', :message => 'Match already exists' }
end
result.to_json
end
create_tournament = lambda do
tournament = Tournament.new
tournament.name = @request_payload['name']
if @request_payload.has_key?('users')
users = @request_payload['users']
users.each do |user_id|
user = User.get(user_id)
tournament.users << user
end
end
result = process_save(tournament)
result.to_json
end
show_tournaments = lambda do
tournaments = Tournament.all
tournaments.to_json
end
update_scores = lambda do
match = Match.get(params[:id])
unless match.kind_of?(Match)
status 404
return { status: 'error', message: 'This match is not in the database' }.to_json
end
if @request_payload.has_key?('scores')
@request_payload['scores'].each do |input_score|
score = match.scores.first(:user_id => input_score['user_id'])
unless score.kind_of?(Score)
status 404
return { status: 'error', message: 'Could not find the given user in this match' }.to_json
end
score.games_won = input_score['games_won']
match.scores << score
end
else
status 400
return { :status => 'error', :message => 'Request body is invalid' }
end
if match.save
status 201
result = { :match => match, :scores => match.scores }.to_json
else
status 500
result = { :status => 'error', :message => match.errors.to_hash }
end
result
end
delete_user = lambda do
user = User.get(params[:id])
result = process_delete user
result.to_json
end
delete_tournament = lambda do
tournament = Tournament.get(params[:id])
result = process_delete tournament
result.to_json
end
delete_match = lambda do
match = Match.get(params[:id])
result = process_delete match
result.to_json
end
delete_score = lambda do
score = Score.get(params[:id])
result = process_delete score
result.to_json
end
delete_player = lambda do
player = Player.get(params[:id])
result = process_delete player
result.to_json
end
update_match = lambda do
match = Match.get(params[:id])
unless match.kind_of?(Match)
status 404
return { status: 'error', message: 'This match is not in the database' }.to_json
end
if @request_payload.has_key? 'match'
match.attributes = @request_payload['match']
end
result = process_save(match)
result.to_json
end
get '/users', &show_users
get '/users/:id', &show_user_detail
get '/users/search/:username', &find_by_username
post '/users', &create_user
delete '/users/:id', &delete_user
get '/tournaments/:id/players', &show_players_in_tournament
post '/players', &add_players_in_tournament
delete '/players/:id', &delete_player
get '/tournaments/:id/matches', &show_matches_in_tournament
post '/matches', &log_match_in_tournament
put '/matches/:id', &update_match
delete '/matches/:id', &delete_match
get '/tournaments', &show_tournaments
post '/tournaments', &create_tournament
delete '/tournaments/:id', &delete_tournament
put '/matches/:id/scores', &update_scores
delete '/scores', &delete_score
# Generic method for processing simple save actions
# @param resource Model - de model that needs to be saved
# @return result Hash - the message that will be displayed to the user
def process_save(resource)
if resource.save
status 201
{:status => STATUS_CREATED, :resource => resource}
else
{:status => STATUS_FAILED, :errors => resource.errors.to_hash}
end
end
# Validates that the match between the two user hasn't been saved before
# @param tournament Model - the tournament where the match takes place
# @param users Array - the two players in the match
# @return Boolean - true if the match doesn't exist, false otherwise
def validate_match(tournament, users)
tournament.matches.each do | existing_match |
scores = existing_match.scores.all(:user_id => users)
if scores.count == 2
return false
end
end
return true
end
# This method is used to keep the code DRY
# @param tournament Model - the tournament for which we are gettting all the data
# @return resource Hash - the complete resource with tournament, matches and scores
def get_tournament_scores(tournament)
matches = []
tournament.matches.each do |result|
match = { :match => result, :scores => result.scores }
matches << match
end
resource = { :tournament => tournament, :matches => matches }
end
def process_delete(resource)
if resource.destroy
status 204
result = {}
else
status 500
result = { status: 'error', message: resource.errors.to_hash }
end
result
end | true |
7bc3a42d8e18b38bd598dfed76b8eb19d7fa6287 | Ruby | Temceo/udemy | /section-18/parse_data.rb | UTF-8 | 786 | 2.890625 | 3 | [] | no_license | system 'cls'
require 'rubygems'
require 'httparty'
class ApiGetter
include HTTParty
base_uri 'https://udemy-api.herokuapp.com'
def rails_users
self.class.get('/users.json')
end
end
data = ApiGetter.new()
data.rails_users.each do |user|
raw_time = "#{user['created_at']} "
parse_time = Time.parse(raw_time)
first_name = "#{user['first_name']} "
last_name = "#{user['last_name']} "
email = "#{user['email']} "
street_address = "#{user['street_address']} "
time = parse_time.strftime('%A, %d %b %Y %l:%M %p')
# print "#{user['id']} "
text_file = File.new('users.txt', 'a')
text_file.puts "First Name: #{first_name}, Last Name: #{last_name}, Email: #{email}, Street Address: #{street_address}"
text_file.close
end
| true |
0ea10b021c7a48b0e737ca71388e10cc94665ac2 | Ruby | morinoko/well-grounded-rubyist | /ch5-self-scope/class-variables-1.rb | UTF-8 | 1,086 | 4 | 4 | [] | no_license | # A simple way to use class variables, BUT should be used with caution,
# they are class-hierarchy scoped (no new scope when inherited)
class Car
@@makes = []
@@cars = {}
@@total_count = 0
attr_reader :make
def self.total_count
@@total_count
end
def self.add_make(make)
unless @@makes.include?(make)
@@makes << make
@@cars[make] = 0
end
end
def initialize(make)
if @@makes.include?(make)
puts "Creating a new #{make}!"
@make = make
@@cars[make] += 1
@@total_count += 1
else
raise "No such make: #{make}."
end
end
def make_mates
@@cars[self.make]
end
end
Car.add_make("Honda")
Car.add_make("Ford")
honda1 = Car.new("Honda")
honda2 = Car.new("Honda")
ford1 = Car.new("Ford")
puts "Counting cars of same make as honda2..."
puts "There are #{honda2.make_mates}."
puts "------"
puts "Counting total cars..."
puts "There are #{Car.total_count}."
x = Car.new("Brand X")
#=> No such make: Brand X. | true |
0810a32313906372b0a1861ce523a4e6d7361e59 | Ruby | leospaula/evotto-test | /lib/csv_parser.rb | UTF-8 | 330 | 3 | 3 | [] | no_license | require 'csv'
class CSVParser
attr_reader :data
def initialize(source)
@data = []
call(source)
self
end
def call(source)
CSV.read(source, { header_converters: :symbol, headers: true }).each do |row|
@data.push({name: row[0], age: row[1].to_i, project_count: row[2].to_i, total_value: row[3].to_i})
end
end
end | true |
4fffeeb71c735a3285396bb9f947de653d1b390d | Ruby | pstivers3/rubylearn | /pippen/1_arrays_and_hashes/1_duplicate_collections/1_validates_constructor_arguments.rb | UTF-8 | 667 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env ruby
class ValidatesConstructorArguments
def initialize(potentially_invalid_array)
@potentially_invalid_array = potentially_invalid_array.dup
raise ArgumentError.new("The passed array is invalid") unless array_valid?
end
def transform
potentially_invalid_array.map { |x| x.upcase }.join(",")
end
private
attr_reader :potentially_invalid_array
def array_valid?
potentially_invalid_array.all? { |x| String === x }
end
end
array = ["string", "string", "string"]
vca = ValidatesConstructorArguments.new(array)
# the next line does not effect the duplicate array formed by the previous line
array << 1
p vca.transform
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.