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

learn more… | top users | synonyms

4
votes
3answers
75 views

Whats 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.inj­ect({}) { |h, el| h[el]­ = a.cou­nt(el) if h[el]­.nil? ; h }.sor­t_by ...
1
vote
1answer
37 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 ...
2
votes
2answers
78 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 ...
2
votes
1answer
86 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
27 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
85 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
81 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
57 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
52 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
62 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
46 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
21 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
52 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
0answers
32 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
79 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
52 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
64 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
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
39 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
47 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
93 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
54 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
65 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
69 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
48 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
69 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
49 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
67 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
62 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
133 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
74 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
89 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
85 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
72 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
41 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
54 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
96 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
56 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
111 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" ...

1 2 3 4 5 6