0
\$\begingroup\$

I am new to Ruby on Rails. Can some one please help me with this question?

How would you modify the following to be consistent with Ruby's style?

class Add_dash
def dashesHere(word)
    attachTheDashes = "--" + word + "--"
        return attachTheDashes
   end
end
\$\endgroup\$

migrated from stackoverflow.com Sep 22 '14 at 10:07

This question came from our site for professional and enthusiast programmers.

9
\$\begingroup\$

Well first your indention is a bit strange, it'd be better like this:

class Add_dash
  def dashesHere(word)
    attachTheDashes = "--" + word + "--"
    return attachTheDashes
  end
end

And you typically don't need return in Ruby, it'll return the last value evaluated in your function. So having that in mind you could write it like this:

class Add_dash
  def dashesHere(word)
    "--" + word + "--"
  end
end

But Ruby also offers a way to easily put any value into a string, without adding a bunch of strings together. It really allows you to put any Ruby code in a string, and whatever it returns, will be put into your string. That looks like this: "math: #{1 + 1}" which would be "math: 2", or "Hello #{name}" would greet who ever was in name.

So you could write your whole thing like this:

class Add_dash
  def dashesHere(word)
    "--#{word}--"
  end
end

And in Ruby class names (Add_dash in your case) are supposed to be written in CamelCase starting with a capital letter. Method names and everything else are written in snake_case.

This would be my final version:

class AddDash
  def dashes_here(word)
    "--#{word}--"
  end
end

I hope this helps!

\$\endgroup\$
  • \$\begingroup\$ Almost: indentation is 2 spaces in Ruby. \$\endgroup\$ – Jörg W Mittag Aug 31 '14 at 10:11
  • \$\begingroup\$ @JörgWMittag I fixed the indentation \$\endgroup\$ – addison Aug 31 '14 at 13:33
2
\$\begingroup\$

I would write it like this:

def dashes_here(word)
  "--#{word}--"
end

It is common in Ruby to use undersores instead of camelcase in method names. The string interpolation is easier to read than string concatination. And since you do nothing be returning the variable, you can skip that past completely. Ruby always returns the last evaluated result.

\$\endgroup\$
0
\$\begingroup\$

Class names should be camel case, method names and variables should be lower case with underscores as word separators.

\$\endgroup\$
0
\$\begingroup\$
class String
  def add_dasherize
    "--#{self}--"
  end
end

'important'.add_dasherize # --important--

Does it make sense to apply this method to anything other than a String? If not, I would just open up String and add the method. Also, the (somewhat silly) Rails convention is use an -ize suffix, as you can see in ActiveSupport::Inflector (which already defines a dasherize).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy