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

learn more… | top users | synonyms

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
49 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
32 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 ...
-2
votes
0answers
34 views

user has_role? please help me to review my code [closed]

this is the user model code: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and ...
0
votes
1answer
53 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
80 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
42 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
122 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
48 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
58 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
84 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
80 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 ...
-1
votes
0answers
26 views

sprintf to convert floating number to integer in ruby [closed]

I was trying to convert a result to integer using the following expression sprintf "%d", (3+ Math.sqrt(5))**28) which gives result as 135565048129406451712 but expected result is ...
4
votes
1answer
117 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
37 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
100 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
69 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
104 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
36 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
93 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
142 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
54 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
98 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
46 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
32 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
40 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
91 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
47 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
87 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, ...
3
votes
2answers
80 views

How can I make this code DRY in my controller?

What is the best way to DRY this code up? class NotificationsController < ApplicationController before_filter :load_user def unsubscribe if @facebook_admin && ...
3
votes
2answers
63 views

Review of OOP in Ruby class

Could you please review the following class products? It should tell me whether the product is taxable or imported. Name should indicate if the product is imported or certain keywords should tell ...
0
votes
1answer
137 views

Why did I fail this Ruby developer test? [closed]

I took this developer test for a potential employer, and they said I failed because of my response to the first question. But Rails for Zombies seemed to imply that that's how you assign data to ...
3
votes
2answers
106 views

An abundance of ternary operators

I'd like to find a way to do what this method does in a cleaner, less hacky looking way def self.create_from_person!(person) spi = new(:person => person, :provider => person.provider) ...
3
votes
2answers
120 views

Help in refactoring this method - Ruby

def divisible?(n) if n % 1 == 0 && n % 2 == 0 && n % 3 == 0 && n % 4 == 0 && n % 5 == 0 && n % 6 == 0 && n % 7 == 0 && ...
2
votes
1answer
22 views

How to refactor that content_tag adding method?

How to get rid of that duplicaiton in if conditional? def set_caption(result) if result.respond_to?(:app_name) content_tag(:div, result.type_name, class: 'type-name') + content_tag(:div, ...
3
votes
3answers
96 views

Most efficient way to iterate through arrays/can I use .times method in place of while method?

I created a quick program to test the precision of randomness generated by the .rand method. The primary question is whether I can use the .times method in place of the while code blocks to increase ...
1
vote
1answer
52 views

Updating / validating mass update rails association

My recipes model is as follows has_many :quantities has_many :ingredients, :through => :quantities, :uniq => true has_many :sizes, :through => :quantities, :uniq => true And the ...
3
votes
3answers
86 views

Best way to include image_tag inside link_to

What is the most elegant and readable way to in include (potentially long) image_tag calls inside of link_to? Example <%= link_to image_tag('buckminsterfullerene.png', width: '210', height: '60', ...
0
votes
0answers
46 views

Is this a good, cross-platform way of spawning processes in Ruby 1.9?

Below is a function I am using to spawn subprocesses in a cross-platform manner on Ruby 1.9 with optional timeout support. It works well most of the time. However I am experiencing a weird issue ...
0
votes
3answers
96 views

How do I generate a list of n unique random numbers in Ruby?

I am trying to create a randomly generated array of x numbers with no duplicates. I am choosing numbers, one at a time, then comparing each new number to the numbers already in the array. Here is my ...
1
vote
2answers
118 views

Ruby implementation of Conway's Game of Life

I'm just starting with Ruby and decided to do two different implementations of Conway's Game of Life. In this first one I'm not using cells as a separate class and instead just track everything as a ...
2
votes
2answers
95 views

Placement of success code in a conditional

I'm not sure if there's a standard view where the placement of a success result should be in a conditional that can return multiple statuses. The success condition of this function is in the middle of ...
2
votes
2answers
101 views

What's the most readable way to write this line of Ruby code?

What is the most readable way to write this in Ruby? if (not url.blank?) and (not url.include?('*'))
-1
votes
1answer
69 views

How to create 3 objects using one form only if each one is valid? [closed]

I want to create Job, Employer and Company using one form. Model class Job < ActiveRecord::Base accepts_nested_attributes_for :company, :employer belongs_to :company belongs_to :employer ...
4
votes
1answer
105 views

Refactor ruby each-code

def users_list html = '' self.users.each do |user| html << user.link_avatar_tag end html.html_safe end I feel that it is possible to write shorter. Is it possible ...
1
vote
3answers
60 views

Dynamic variables in loop

I have this working code. I think this must be easier with a while loop. if not c.e1.nil? extrapreis = number_to_currency Extra.find(c.e1).aufschlag, :unit=>"EUR " array.push ...
1
vote
2answers
120 views

iterate over an array and delete elements conditionally

The following logic: Iterate over the URLs array and If the HTTP request with the given URL does not timeout, continue. If the URL times out, remove it from the array and continue with the next one ...

1 2 3 4 5