Today, while creating a ton of very long method names (for temporary readability while refactoring), I decided the underscore was too hard to press.

The result is this function. Anytime space is pressed between “def “ and newline but not between “(“ and “)” it will insert “_” instead of “ “.

Enjoy:

(defun kdt-ruby-method-space-replace ()
  "When pressing space while naming a defined method, insert an
underscore"
  (interactive)
  (if (and (looking-back "def .+")
	   (not
	    (and
	     (looking-at ".*)$")
	     (looking-back "(.*")
	     )
	    )
	   )
	   (insert "_")
	   (insert " ")
	   ))

(eval-after-load 'ruby-mode
  '(progn
     (define-key ruby-mode-map (kbd "SPC") 'kdt-ruby-method-space-replace)
     ))

UPDATE

As suggested on Reddit by zenspider, here it is in idiomatic elisp:

(defun kdt-ruby-method-space-replace ()
  "When pressing space while naming a defined method, insert an underscore"
  (interactive)
  (if (and (looking-back "def .+")
           (not (and
                 (looking-at ".*)$")
                 (looking-back "(.*"))))
      (insert "_")
    (insert " ")))

(eval-after-load 'ruby-mode
  '(progn
     (define-key ruby-mode-map (kbd "SPC") 'kdt-ruby-method-space-replace)))

Until next post!