Ruby is a dynamic, open source programming language with a focus on simplicity and productivity.
0
votes
1answer
68 views
+150
Review my ruby for performance
So I'm using the acts_as_taggable_on gem to tag 3 different models: Question, Blog, and Video
Each one has a site_id to distinguish which site they show up on (SaaS-ish).
I wanted to get all tags ...
1
vote
3answers
51 views
Shortening a multitude of && evaluations in this if statement?
I have these two functions and I was just wondering if there is any way to shorten the line of code with the many && statements. Shortening of the rest of the code would be cool too, but it's ...
0
votes
0answers
42 views
Am I correctly testing that methods from Kernel have been called?
Any time I'm testing a Ruby class that calls a Kernel method such as sleep or exit, i define a singleton method on the class instance and test that it has been invoked:
it "must throttle requests" do
...
1
vote
1answer
47 views
content_tag concatenation clean up
I need to concatenate two content_tag and it works but it seems a little messy to me. Any thoughts on how may I refactor this?
def format_price(money)
mny = get_price_string(money).to_money
str = ...
1
vote
1answer
56 views
define_method vs method_missing and CodeClimate scores
This may be a better fit for another board, but here goes:
I've made a very simple gem that acts as a days-of-the-week bitmask. To be hip, I registered it on CodeClimate, where it's currently scoring ...
1
vote
0answers
34 views
Rails service + oauth code structure
I'm having trouble structuring the logic of OAuth integration into my web app. In the app, a user creates a Report that consists of data from their google analytics account.
User steps:
User clicks ...
1
vote
3answers
55 views
Ruby: Code review
I have recently started using Ruby and would like to hear your take on the following piece of code.
class Generator
def initialize
@context = nil
end
def start(params)
@context = ...
2
votes
2answers
47 views
Should I be using Regex to uppercase uncommon characters?
I've written a function for converting strings to upper case. It currently works by replacing each character using a Regex pattern with a hash:
# Special upcase function that handles several ...
2
votes
1answer
58 views
What is the best practice for working with a project as nested modules?
I come from the world of Python, so I'm used to every file representing their own enclosed module, never polluting the global environment. Up until now (I've worked with Ruby for a week) I've created ...
1
vote
2answers
54 views
Manipulate Hash to typecast true/false for certain values
is there a better why how can I refactor this code, making sure that values in a Hash are typecasted to true/false if their value is '1' or '0' while leaving unaltered the rest?
I'm using Ruby 2.0.0 ...
0
votes
1answer
60 views
Quick and dirty command line application in Ruby. Now it's time to refactor, where should I start?
#!/usr/bin/env ruby
require 'pivotal-tracker'
require 'yaml'
TEMP_DIR = "#{ENV['HOME']}/.pivotal/"
TEMP_FILE = TEMP_DIR + "temp.yml"
CONFIG_FILE = TEMP_DIR + "config.yml"
unless File.directory? ...
5
votes
3answers
149 views
What's a good way to create a sorted hash counting the occurances of a number in an array in ruby?
I figured something like this
a= [1, 2, 3, 2, 2, 2, 3, 1, 1, 1, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a.inject({}) { |h, el| h[el] = a.count(el) if h[el].nil? ; h }.sort_by ...
1
vote
1answer
57 views
DRY up Rails Navigation Code
In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i ...
3
votes
3answers
194 views
Ruby multiples of 3 and 5 code challenge
I have implemented the first coding challenge on http://projecteuler.net/. I would love to get it reviewed by some expert rubyists! Thanks in advance :)
# Multiples of 3 and 5
#
# If we list all of ...
4
votes
2answers
147 views
Trying to get better at Ruby and programming in general- here's a simple TopCoder question in Ruby
I want to get general feedback and feedback about if I can make this more Ruby-like, if there are any obvious inefficiencies, and if I need to organize my class differently. The topcoder question is ...
1
vote
1answer
34 views
Clean up Rails Routes
Is there any way I can DRY up this Rails 4 routes.rb code?
match '/oauth/apps/' => 'oauth/applications#index', :as => :oauth_applications, :via => :get
match '/oauth/apps/new/' => ...
0
votes
3answers
93 views
Tell me how to improve my code?
I am a redneck coder that I was not happy! How can I improve this code:
def show
if params[:type]=="all"
if params[:dir] =="next"
@work = Work.find(:first, :conditions => ["id > ? ...
3
votes
1answer
86 views
Is my solitaire cipher too imperative for an Object Oriented language like Ruby?
I am teaching myself Ruby and Ruby-on-rails, as part of this regimen I thought it would be a good idea to do some Ruby quiz exercises and so I started with the solitaire cipher. The basic ...
3
votes
2answers
63 views
How to refactor this Ruby method?
The new_string code in this method does not seem idiomatic.
The goal is to not mutate the string passed in, which I believe is a good practice.
This method changes all URL's in the string into an ...
3
votes
2answers
55 views
Best way to AND two hashes?
I need to exclude from a hash the keys not present in another hash, but the Hash class doesn't have a & operator do this, for example:
Hash[model.to_a & model2.to_a]
Is there a better way to ...
3
votes
1answer
71 views
Lowest Common Multiple of 1 to n in Ruby
Project Euler problem 5 asks:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I'm learning Ruby by going through Project Euler problems, and ...
-1
votes
0answers
50 views
New library for declaring units on numerical model attributes
A couple of days ago as I was working on a project I stumbled something I consider a problem and that, as far I know, doesn't have any good solution available in Rails.
The problem is attribute ...
1
vote
0answers
31 views
Dynamic Controller Creation in Rails
I have overrode Rails' ActionDispatch::Routing::RouteSet::Dispatcher.controller_reference method to check if a controller exists by checking for the required constants and then creating them based ...
2
votes
1answer
56 views
Drawing game objects using their Z-order property
I am creating a game, with Ruby scripting.
Sprite and Label objects can be drawn on the screen. Depending on the order you draw them, one will overlap the other.
To make things easier, I want to ...
2
votes
1answer
44 views
Ruby Branch and Bound Algorithm implementation?
I am relatively new to Ruby and am trying to get a handle on making my code more Ruby-esque. At the same time I am experimenting with the branch and bound algorithm to solve a problem that I outline ...
4
votes
1answer
83 views
Ruby: refactor simple string method for aligning DSV text
GOAL:
Accept DSV strings where the delimiter may consist of more than one character
Accept DSV strings where there are no embedded delimiters
Output text with no modification to the source string ...
2
votes
1answer
57 views
How do I refactor this ActiveRecord object to lessen dependency on callbacks?
I have an Order object that belongs_to a BillingAddress and a ShippingAddress. I want to present my user with only ShippingAddress fields and a checked checkbox indicating that the billing address ...
2
votes
1answer
72 views
Mapping arrays to ranges in Ruby
I have a simple Rails app, which is used to run some clinical surveys. Participants answer sets of questions (multiple-choice, valued 1-5), and, within each set, the answers are summed up and the ...
1
vote
1answer
46 views
Ruby script to send PragPub magazine to Kindle
I wrote a little ruby script to download issues of PragPub magazine and send them to my Kindle via email. I would love to get some feedback on it.
One part, specifically, where I feel like there ...
0
votes
0answers
31 views
Improvements on tree index class
I developed a QuickIndex class which serves to index arrays of stringafiable objects using a tree structure. The purpose is to then primarily to allow for fast index or include? method calls directed ...
1
vote
1answer
49 views
Ruby Game of Life with matrices
A little while ago I wrote this implementation of Conway's Game of Life in Ruby. It's based on this Game of Life in APL video, which I think is rather elegant, though a bit dense. Feel free to give ...
2
votes
3answers
51 views
Ruby: check if email address contains one of many domains from a table, ignoring the subdomain
I'm trying to validate email addresses as being from certain universities. I have a table, 'University', which is full of university domains. University email addresses often have different ...
1
vote
3answers
102 views
Project Euler problem 37: truncatable primes
I am working on Project Euler problem 37 and I have the following program:
#!/usr/bin/ruby -w
require 'prime'
h=11
y=0
x=0
while x < 11
if h.prime? == true
boo = true
f=0
...
1
vote
2answers
55 views
speed up square digit function
for the following function
#!/usr/bin/ruby -w
e=0
g=0
h=1
while h < 10000000
a = h
f=0
while f !=1 && f!= 89
d=0
f=0
while a.to_s[d] != nil
...
0
votes
2answers
59 views
A pattern to destructively extract items from an array
I want to efficiently (few intermediate objects) and neatly (few lines and easy to read) filter an array, removing and returning rejected items. So like a call to delete_if except instead of returning ...
0
votes
2answers
67 views
Re-factoring amateur ruby code
I am new to ruby and I would be grateful if I need help with re-factoring my code.
class Beam
def initialize
puts "Please specify span of beam"
@span = gets.chomp.to_f
puts "How many ...
1
vote
2answers
77 views
Quicksort in Ruby!
I've been teaching myself Ruby this weekend. First of all, I am aware that there is a built-in sort function. I've written this code strictly as an exercise.
I have background primarily in C# and ...
0
votes
2answers
46 views
ruby notes scrubber search for specific characters [closed]
I am looking to making a not scrubber for my testing notes. I want to run a script that will read the entire file looking for special "tags" that I made in my notes, like @ ? (c) etc...
I then want to ...
1
vote
2answers
50 views
How can I make an easy to understand subtraction accumulator?
I'm currently following the tutorials over at RubyMonk, and one of the problems I need to solve is to write a subtract function that would meet these conditions:
invoking subtract(4, 5) should ...
2
votes
1answer
72 views
General case of the 24-challenge problem
I'm working on an algorithm to solve the 24-challenge game. The basic idea is to combine positive integers using arithmetic operators to produce an expression that evaluates to exactly 24. For ...
0
votes
1answer
52 views
Suggestions for Ruby string parsing
I need to add quotes to each word in a string. Here is something that works but it looks ugly to me;
"this is a test".split.to_s.delete("[],")
produces
"\"this\" \"is\" \"a\" \"test\""
split ...
0
votes
1answer
69 views
Math Calculus in ruby
I have several calculus to do in my ruby app.
My code is currently working but I find it very ugly.
@guestreviews = GuestReview.where(:reviewed_id => @user.id)
@hostreviews = ...
1
vote
3answers
95 views
Optimizing sum_combination_for(n) code
I'm working on a piece of code for calculating all the possible combinations of numbers that sum to n. For example:
sum_combination(3) = [
[1,1,1],
[1,2],
[3]
]
So my ruby code is this:
...
1
vote
1answer
75 views
Rails: Setting a transient attribute on a set of objects from one model based on information from a junction model
I have a user model, a task model, and a junction model user_task that saves the data joining the two:
class Task < ActiveRecord::Base
attr_accessor :completed_on
has_many :user_tasks
class ...
3
votes
1answer
135 views
Nasty Age Printing Method
I have this ugly age printing method. Can you do better?
def age(birth_date)
today = Date.today
years = today.year - birth_date.year
months = today.month - birth_date.month
(months -1) if ...
3
votes
2answers
54 views
Preventing Division by Zero
numerator: Value being divided.
denominator: Divisor value.
method so far:
def calc_percentage(numerator, denominator)
((numerator/ (denominator.to_f.nonzero? || 1 )) * 100)
end
What are the ...
1
vote
4answers
83 views
can this rails code be simplified and be more efficient? nested if else statements
Here's a part of my controller and it's getting quite lengthy (the code works).
Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently?
def ...
1
vote
3answers
93 views
How to flatten the nested for loops?
The problem I am facing is:
I need to interate through a bunch of lists, and there are separated conditions which needs to be satisfied by the list. conditons are not independent.
I care about the ...
1
vote
1answer
87 views
Optimizing code for project-euler p#23
I'm working on project euler's problem #23, wich is
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers
So I came up with this algorithm. Find ...
4
votes
1answer
120 views
Refactor a sequence of functions
I have an http library in Ruby with a Response class, I have broken it down into smaller methods to avoid having a big intialize method, but then I end up with this:
def initialize(res)
@res = ...