Ruby is a dynamic, open source programming language with a focus on simplicity and productivity.
2
votes
2answers
57 views
Removing list of words from a text file in Ruby
I have two files.
File 1. Has a list of all the dictionary words
File 2. Has a list of
all prepositions.
I want to remove all the prepositions from the dictionary.
I want to reduce the number of ...
2
votes
1answer
57 views
Refactoring a Delimiter
Is there a more cleaner approach to this? I'm doing the String calculator Kata posted by Roy Osherove. I realized that my calculator has no way of clearing out a previous expression after calling add. ...
0
votes
0answers
28 views
Array variable loses reference while looping [on hold]
I have two questions:
Is there a way to streamline this code from an object-oriented perspective?
I am writing a parsing routine in Ruby 2.1 for a spreadsheet. The code works properly through the ...
4
votes
4answers
77 views
Reduce cyclomatic complexity
How can I reduce cyclomatic complexity of validation and refactor it better way?
def valid?
return false if @opts.nil?
return false if @opts[:property_1].nil?
return false if ...
-2
votes
0answers
15 views
Using Win32API to get MouseWheel input [on hold]
I'm trying to use win32api to get mouse wheel input on Windows MSDN.
I tried the following:
@state = Win32API.new('user32','DefWindowProc',['i'],'i')
p @state.call(0x0800)
But it keeps returning 0 ...
-2
votes
0answers
20 views
Problem with EvernoteClient (very slow pageload) [closed]
At the moment I am trying to create an EvernoteClient with Ruby and Sinatra. Right now I have a really big problem and I don't know how to solve it. The problem is my application works really really ...
0
votes
1answer
32 views
Implementing plugins in my Ruby social aggregator app
Some time ago I started with a small Ruby project. I call it social_aggregator.
This software aggregates information from different networks to one xml-stream, which you can reuse. For instance on ...
3
votes
1answer
42 views
Booting up my Ruby social aggregator app
Some time ago I started with a small Ruby project. I call it social_aggregator.
This software aggregates information from different networks to one xml-stream, which you can reuse. For instance on ...
7
votes
1answer
81 views
Faster way to find maximum deviation?
So, it was a part of my coding challenge and the last one, but I failed because it failed to yield a result in two seconds for some of sample inputs (out of six samples, three passed but three failed ...
8
votes
3answers
121 views
Counting words / lines in Ruby - more compact / idiomatic way?
I solved this problem in Ruby:
Write an utility that takes 3 command-line parameters P1, P2 and P3.
P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take
the values:
...
7
votes
2answers
86 views
Shorter, better way to write a “query” involving virtual attributes
I have this code in a model for an invoicing app. This virtual attribute current_invoice gets the only non-rescinded invoice associated with a contract. The code works but it seems really verbose. Can ...
5
votes
2answers
60 views
How to properly call an “upsert” using parameterized raw SQL to Postgresql in ActiveRecord?
I need to call an upsert to my Category table in PostgreSQL. My current solution uses the exec_query API in ActiveRecord, using binding.
What I got so far looks like this:
VERIFY_CATEGORY_SQL = ...
6
votes
2answers
53 views
Nested trial and error in if-else condition
Using Rails 3.2, I have the following:
g = Geocoder.search(address)
# if no address found, geocode with latitude and longitude
if g.empty?
g = Geocoder.search(latitude, longitude)
if g.empty?
...
4
votes
2answers
45 views
Scraping and analyzing recent articles on bitcoin
This script scrapes recent articles on bitcoin, does sentiment analysis, and does some mock trading based on the sentiment of the articles. I'm looking for advice on code style, and I would love to ...
10
votes
6answers
561 views
Help refactor this to be less procedural and more recursive
Reference: Is this a faithful rendition of the selection sort algorithm?
I'm working through an elementary book on sort and search algorithms, and writing some sample code to test my understanding. ...
8
votes
2answers
130 views
Search for directories with a certain prefix that contain no files of a given type
These two functions search for directories with a certain prefix that contain no files of a given type.
Does the code adhere to Ruby standards and conventions?
Am I doing something the hard way or ...
5
votes
3answers
88 views
Small guessing game in Ruby
I'm writing a small guessing game. I'm writing a points calculation algorithm.
I wrote the following, and it works. But I feel like I'm bringing over procedural background into Ruby, or not ...
3
votes
1answer
39 views
Serializing tabular data in ruby — is map, flatten, hash the correct approach?
I wanted a hash which lets me reference Japanese syllables by their romanized names. In hindsight I could have searched for an existing one column table, but I wanted to improve my ruby by writing a ...
3
votes
2answers
85 views
Shorten code that gathers files from directories
I have the following method in Ruby that appears to be just one line too long according to Ruby style guides. (Specifically: Rubocop tells me that my method has too many lines.)
Granted, I'm only one ...
2
votes
1answer
71 views
Code reuse while keeping meaning clear and avoiding unforseen consequences
I like to reuse code as much as possible and keeps things DRY. But I'm afraid that sometimes it creates too many layers of indirection. It then becomes a chore to find where code exists that is ...
5
votes
2answers
78 views
Make this Ruby array pivot more efficient?
A puzzle I was given:
Description:
Write a method that returns the "pivot" index of a list of integers.
We define the pivot index as the index where the sum of the numbers on
the left is ...
2
votes
1answer
33 views
Pig Latin Translator in Ruby and Rspec
PigLatin Kata
PigLatin Kata
Create a PigLatin class that is initialized with a string
- detail: The string is a list of words seperated by spaces: 'hello world'
- detail: The string is ...
0
votes
0answers
17 views
Ruby module namespacing advice [migrated]
in my current project have:
module Stats
class Site
...
end
class Product
...
end
class Profile
...
end
end
now in my Product class have methods to get/set product ...
4
votes
3answers
56 views
Number to words problem
This is a very long solution I've been working on to a Number to Words problem. I've identified that there's a lot of repeating logic (e.g. 'if writing > 0', 'writing = integer /',).
How would you ...
4
votes
1answer
53 views
Printing some metrics from a Windows machine
New to Ruby here. I just made a script that print some metrics from a Windows machine about its disk. The script works fine and as I wanted it to. Now, since I'm new to the ruby and programming world, ...
6
votes
2answers
86 views
Return input as a partial fraction
I need to write a function that, when given an input (string, float, or int), returns that input as a reduced partial fraction, and it needs to accept a wide array of inputs:
1.5 => "1 1/2"
5/2 ...
4
votes
2answers
119 views
Ruby and cyclomatic complexity
I'm currently writing a script and I decided to run cane over it to look for some issues, and the following method was highlighted. I've done my best to cut it back, and at this point I'm inclined to ...
4
votes
1answer
100 views
Refactoring multistep form rails
I've implemented just as Ryan Bates suggested in his railscast episode, I've got everything working just right, so here is his approach in the controller :
def new
session[:order_params] ||= {}
...
4
votes
2answers
65 views
Processing array of objects into two strings
I have an array of Item objects that each have a string particular and a numeric amount. I want to put all particulars (separated by newlines) into a single string and the same for all amounts.
...
1
vote
1answer
53 views
Refactoring multi if, if possible
I have fully working code, however I'd like to make it nice. I've got these three models:
1. User(can have both or either one)
user can have one trucker
user can have one owner_trucker
2. ...
3
votes
3answers
58 views
How to write save block code like this more elegant in Ruby?
I have a class Creator which will execute a block code for a number of times. I'm not sure how to write this in a more elegant way in Ruby.
class Creator
attr_accessor :block
def ...
2
votes
3answers
117 views
Pig Latin Code Kata
I've just complete a Pig Latin translator as a code kata and I was hoping someone would review it for me.
Here is the kata:
PigLatin Kata
Create a PigLatin class that is initialized with a string
...
4
votes
2answers
46 views
A better way to set defaults in a Ruby options hash?
I have a specific method that I like because it lets me decide whether or not I want to use the default. If I want anything different I enter in :option => value otherwise I get the default. Here's ...
1
vote
1answer
69 views
How can this rails controller test be cleaner refactored?
I tend to write quite explicit tests for my rails controllers exposing APIs with two seperate concerns:
meeting the defined API-Response with headers headers and the response itself
ensuring the ...
8
votes
3answers
115 views
How clear is this ruby code?
Elsewhere, there was a question about an elegant solution to a problem.
I'm curious whether this solution is elegant from the perspective of easy to understand for a ruby programmer (which I am no ...
2
votes
1answer
70 views
Render dynamically vertical tabs and set classes depends on if statement
I would like to refactor code below and get rid of if statements for classes from view.
.container
.tabbable.tabs-left
%ul.nav.nav-tabs
- @related_tasks.each do |task|
%li{class: ...
0
votes
1answer
76 views
Rails validating with condition block
Rails AR. validate one field, with 4 validators & 2 condition block
validates :inn,
presence: { if: -> { user.is_a?(Client) } },
inn: { if: -> { user.is_a?(Client) } },
...
3
votes
2answers
101 views
Simple fuzzy text search algorithm
Basically, this code takes a keyword and an array of strings, then sorts them based on two things: the number of characters shared with the key, and the distance between them.(As a side note, would ...
8
votes
1answer
203 views
Hot 18 game (modified Blackjack)
I've just completed my first Ruby game. It's a modified BlackJack type game, called Hot 18.
I've used all methods for this Ruby game. It's a one-player game, but you can play with 1, 2, or 3 hands.
I ...
2
votes
1answer
61 views
Sleep and background wakeup system
I'm looking for code review of part of my replacement of timeout() project. Namely, feedback on SleeperNotifier class:
https://github.com/ledestin/frugal_timeout/blob/master/lib/frugal_timeout.rb#L125
...
10
votes
1answer
136 views
Ruby Sudoku solver
This week's weekend challenge #3 seemed like a great opportunity to learn Ruby! Unfortunately, my workload and looming vacation did not cooperate. :( The puzzle will make forced moves automatically, ...
5
votes
2answers
257 views
Splitting a text file into paragraphs and words
I'm iterating through a number of text files, trying to locate all carriage-returns, and individually save the text between carriage-returns. I get the index numbers of all carriage-returns, but I ...
4
votes
2answers
59 views
Ruby Dynamic Struct - Pattern or AntiPattern?
There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. Basically
I used method_missing to return/set values in the ...
3
votes
1answer
45 views
Clone array elements when multiplying by a scalar
Update: Way to bury the lead. ;) The main question here is how best to make sure each array element is a separate string instance.
I am building an array of strings to form the "empty" ...
5
votes
1answer
87 views
How to refactor many small but similar classes in Ruby?
I have classes like these:
class DepartmentSerializer < Serializer
self.root = false
attributes :id, :name
has_many :employees, serializer: EmployeeSerializer
has_one :location, ...
4
votes
4answers
72 views
Help in deciding how to represent a long regular expression
I wrote a simple Polynomial class:
class Polynomial
def initialize(coefficients)
@coefficients = coefficients.reverse
end
def to_s
return '0' if @coefficients.all?(&:zero?)
...
12
votes
1answer
256 views
Weekend Challenge: Ruby Poker Hand Evaluation
I'm late to this weekend challenge (sorry), but since it's all in good fun, I hope that's ok. I'm no poker player, though, so I may have completely overlooked something.
The Hand class does the ...
2
votes
2answers
120 views
rand number generator with limits in ruby
I have an array of 1000 numbers, randomly generated. 10 of those numbers must be between 0-9 (including 0 and 9), and 10 of those numbers must be between 991 and 1000 (including 991 and 1000). This is ...
3
votes
2answers
86 views
How do I refactor lines of Ruby code that run too long due to method chaining or object instantiation?
Here are a couple of examples of one-liners that go way beyond 80 characters:
scope = DepartmentRepository.includes(:location).by_account(@request.account_id).find(approved_department_ids)
...
4
votes
1answer
84 views
Better way to calculate shopping cart discount?
I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount
def get_discounts
@items.each do |name, attr|
...