elegance

How to convert an alphanumeric phone number to digits

UPDATE: The final version of my utility looks like this: StringBuilder b = new StringBuilder(); for(char c : inLetters.toLowerCase().toCharArray()) { switch(c) { case '0': b.append("0"); break; case '1': b.append("1"); break; case '2': case 'a': cas...

What is the correct way to convert from a for loop to a while loop?

I have a for loop of the form: for (int i = from; i < to; i++) { // do some code (I don't know exactly what, it is subject to change) } And I want to convert it to a while loop (mostly because I want to play with the value of i inside the loop to go backwards and forwards and my co-worker thinks that doing this in a for loop is pron...

Version number comparison

Python must have a more elegant solution to this ... maybe one of you can help: I want to write a cmp-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections. Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1. Desired function outputs are mycmp('1.0', '1'...

Making generic before_filters a little less ugly?

Hey folks, I have a few before filters which I am using to control access to resources on a resource-by-resource level. The basic idea is as follows: A user can be a user or admin and can have access to specific resources based on an "accesses" table. Resources/methods can be limited in access to admin, owner, particular users, or eve...

More elegant way to do this in Ruby

I've started with Ruby and am finding new, shorter, elegant ways to write code everyday. In solving Project Euler problems, I've written a lot of code like if best_score < current_score best_score = current_score end Is there a more elegant way to write this? ...

How to improve the way I browse an array with .each while trying to keep track of the index ("i") using Ruby?

Let's say I'm doing a simple .each but I still want to keep the position in the loop, I can do: i = 0 poneys.each do |poney| #something involving i #something involving poney i = i + 1 end This doesn't look very elegant to me. So I guess I could get rid of the .each: for i in 0..poneys.size-1 do #something involving i end ...

Doubly Linked Lists and Trees: To use or not to use?

I've always been taught that the more pointers you need in a piece of code, the less elegant it is. Also, I know that the only data structure that you 'need' is a singly linked tree. As a result, I've always tried my best to avoid such atrocities as doubly linked lists and doubly linked trees. Is this true? Is code really inelegant if...

(T-SQL) Check if a procedure exists before creating it.

I decided to edit my post since people didn't quite get what I'm trying to do (I suppose it was not irrelevant to say why I needed it after all): Ok, there we go. The thing is, I have a HUGE SQL script which many clients use and it has to be ran thoroughly every time a client executes the "database management" functionality that our sof...

Pattern: Elegant way to do something upon function exit?

I have a function with logic that looks like this: doStuff1() try: doStuff2() except type1: error1() return endstuff() except type2: error2() return endstuff() except: error3() return endstuff() if doStuff3(): error4() return endstuff() doStuff4() return endstuff() As you can see, endstuff() is do...

Setting anonymous function scope of 'this' in jQuery utility / ajax methods

As noted in this blog post you can set the scope of this in an anonymous function in Javascript. Is there a more elegant way of scoping this in the anonymous function call on success of the AJAX request (i.e. not using that)? For example: var Foo = { bar: function(id) { var that = this; $.ajax({ url: "www.somedomain...

Optimisation of Ruby algorithm for grouping and counting colours.

Hi, i have what seems on the surface a simple problem which i wish to solve using ruby, i have a bunch of colours with associated photo id's, e.g [[1,"red"],[1,"green"],[2,"red"],[3,"yellow"],[4,"green"],[4,"red"]] and i wish to process the data so that it is in this format: 2 photos for red,green 3 photos for red 1 photo for yellow ...

Get the nth item of a generator in Python

Is there a more syntactically concise way of writing the following? gen = (i for i in xrange(10)) index = 5 for i, v in enumerate(gen): if i is index: return v It seems almost natural that a generator should have a gen[index] expression, that acts as a list, but is functionally identical to the above code. ...

Passing extra data to find_or_create

Something I've always wondered about rails is the ability to pass extra data to find_or_create methods in rails. For example, I can't do the following User.find_or_create_by_name('ceilingfish', :email => '[email protected]', :legs => true, :face => false) I could do u = User.find_or_create_by_name('ceilingfish') u.update_attributes(...

Elegant ruby syntax to return the greater of two objects

Of course there are a thousand ways to get this done, but is the simplest (or most elegant) way to achieve this? [4,8].max That's actually not too shabby, but what would you do? ...

Elegant check for null and exit in C#

What is an elegant way of writing this? if (lastSelection != null) { lastSelection.changeColor(); } else { MessageBox.Show("No Selection Made"); return; } changeColor() is a void function and the function that is running the above code is a void function as well. ...

What is the most elegant way to validate the presence of ONLY one out of two attributes using Rails?

class Followup < ActiveRecord::Base belongs_to :post belongs_to :comment end This model needs to only have either a post or a comment, but only one of the two. Here's the rspec for what I'm trying to do: it "should be impossible to have both a comment and a post" do followup = Followup.make followup.comment = Comment.m...

Pythonic mapping of an array (Beginner)

Hey StackOverflow, I've got a question related to a beginner Python snippet I've written to introduce myself to the language. It's an admittedly trivial early effort, but I'm still wondering how I could have written it more elegantly. The program outputs NATO phoenetic readable versions of an argument, such "H2O" -> "Hotel 2 Oscar", or ...

Whats the most elegant way to rearrange an associative array?

Suppose you have an associative array $hash['Fruit'] = 'Apple'; $hash['Name'] = 'Jeff'; $hash['Car'] = 'Ford'; and you cannot change the order in which these variables are created. So Car is always added to the array after Name, etc. What's the prettiest way to add/move Car to the beginning of the associative array instead of the end ...

More elegant way to write this?

Hi, I am trying to make a multi-dimensional array of characters in ruby, and this works, but is there a more elegant way? def initialize(text) @map = Array.new i = 0 text.split("\n").each do |x| @map[i] = x.scan(/./) i += 1 end #@map = text end#constructor ...

Have I taken a wrong path in programming by being excessively worried about code elegance and style?

I am in a major stump right now. I am a BSIT graduate, but I only started actual programming less than a year ago. I observed that I have the following attitude in programming: I tend to be more of a purist, scorning unelegant approaches to solving problems using code I tend to look at anything in a large scale, planning everything be...