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
4 Answers 4
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!
-
\$\begingroup\$ Almost: indentation is 2 spaces in Ruby. \$\endgroup\$Jörg W Mittag– Jörg W Mittag2014年08月31日 10:11:48 +00:00Commented Aug 31, 2014 at 10:11
-
\$\begingroup\$ @JörgWMittag I fixed the indentation \$\endgroup\$addison– addison2014年08月31日 13:33:03 +00:00Commented Aug 31, 2014 at 13:33
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.
Class names should be camel case, method names and variables should be lower case with underscores as word separators.
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).