Ruby is a dynamic, open source programming language with a focus on simplicity and productivity.

learn more… | top users | synonyms

1
vote
0answers
4 views

Ruby: Best way to AND two hash?

I need to esclude from hash the keys not present in other hash. Because Hash class doens't have a & operator do this with: Hash[model.to_a & model2.to_a] There a better ways to do this ...
2
votes
1answer
35 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 ...
0
votes
0answers
27 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
14 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
43 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 ...
1
vote
0answers
24 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
75 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
46 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
60 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
44 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
29 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 ...
0
votes
0answers
32 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
42 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
90 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
53 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
53 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
61 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
63 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
45 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
44 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 ...
0
votes
0answers
8 views

How do you have threads in Ruby send strings back to a parent thread [migrated]

I want to be able to call a method that repeats x amount of times on a separate thread that sends messages such as "still running" every few moments to the console while I am free to call other ...
2
votes
1answer
68 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
46 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
63 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
84 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
54 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
132 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
52 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
70 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
87 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
83 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 = ...
0
votes
0answers
38 views

A Ruby file-find strategy with the Find library?

I recently wrote a bit of code to fix broken aliases. (A dropbox backup changed all their types to look like true files) I iterate through all files in O(m•n) form. I recognize that there are ...
1
vote
2answers
104 views

Splitting a range into min and max?

I needed to get the minimum and maximum date values from a query using the Sequel ORM in Ruby from my database. Sequel has a range method that returns a Range value. I'm having it return values from a ...
2
votes
3answers
71 views

I need help refactoring some Rails code that looks clunky.

I would like to refactor this block, it looks clunky: # refactor me receive_payment_on = false config[:sections].each do |section| if section[:applicants] section[:applicants][:sections].each ...
1
vote
4answers
106 views

How can I refactor these while and unless loops to be DRYer?

I have a pack of cards and I am doing a 'deal' action. I am dealing n number of cards, for now to one player. How can I dry up the while and unless loops to be fewer lines? def ...
1
vote
1answer
79 views

Three pitchers with water problem?

I don't know what this problem is named, so i can't Google for a solution about it. Here's the image: There are three pitchers with capacities of 10, 7 and 3 quarts. We need to move the water from ...
1
vote
1answer
40 views

Refactor making a tree with hash input?

I initialized a tree using a nested hash as input, but when I recursively call Tree.new on the children, it doesn't seem to pass each child as a hash. As a pretty ugly, but working, alternative, I ...
2
votes
1answer
53 views

two or more render/redirect in the same method

I often have method like this one with two or more render to do due to catching the error for example. I currently do something like this: def update @user = current_user if ...
2
votes
1answer
95 views

Leap year algorithm?

I wrote two functions for determining leap years. ("Kabisat" means "leap year" in Indonesia.) def kabisat? y return false if y%4!=0 return true if y%100!=0 y%400==0 end ...
1
vote
4answers
144 views

Double conditional : Cleaner way to write a set of conditionals

Is there a cleaner way to write: def b_fname if mdes_version_is_after?(3.0) result = c_fname else result = response_for("#{birth_baby_name_prefix}.BABY_FNAME") end if ...
0
votes
0answers
55 views

Mixin both instance and class methods in Ruby

I have a Ruby class into which I want to include both class and instance methods. Following the pattern described in "Ruby Pattern: Extend through Include", I'm currently using the following: class ...
3
votes
2answers
103 views

How would one more elegantly parse data from XML using Ruby and Nokogiri?

I have a method that parses XML into an array of hashes. Here is the original XML: <rowset name="skillqueue" key="queuePosition" ...
2
votes
1answer
47 views

Rails helper method refactor

I have this messy helper method: def gesture(klass, item, text, desc) element_class = klass.to_s + " gesture" content_tag :li do if klass == :sell link_to new_reply_path(item_id: ...
4
votes
2answers
64 views

Refactor Ruby method for getting domain?

How do I make this more Ruby like? I want to return the host, for example if the URL is "http://www.facebook.com" then I want to get 'facebook.com'. Any other sub-domains without 'www' should give ...
0
votes
1answer
33 views

What is the best way to format a large has_many through line?

This question is about code style. I have this line in one of my models: has_many :owning_artists, :through => :artist_tracks, :source => :artist, :conditions => { :artist_tracks => { ...
2
votes
1answer
44 views

Refactor Ruby ActiveRecord importing library

In my Rails app I need to import some files from CSV and Excel files. I needed it in 2 models so I have written lib/importable.rb: module Importable def self.included(base) base.send :extend, ...
3
votes
1answer
98 views

code optimization in ruby

I'm trying to solve the four color theorem in ruby. A map is like this: ccaaaa baaadc babcdc bbbcdc abcccc And so far i have this following code but it's slow, how could I make it better ? ...
2
votes
1answer
48 views

Ruby persistent file open best practice

I have a method opening and appending to a file as so: def writeFile(ofile,number) File.open(ofile, 'a') { |file| file.puts(number) } end Which is called after line processing by another method. ...
1
vote
1answer
89 views

How can I make this code DRY and KISS in my model?

class Rating < ActiveRecord::Base attr_accessible :item_type, :item_id, :rating, :voters_up, :voters_down serialize :voters_up, Hash serialize :voters_down, Hash belongs_to :ranks, ...

1 2 3 4 5 6