0

I have a YAML file that uses the encoding __firstname__ as a placeholder which signifies that an existing method firstname should be used, rather than the literal string in a subsequent process.

I am trying to understand the most ruby way to to do this. Basically, I need to extract the part between the underscores and send it to an object. Here is pseudocode:

variable = '__firstname__'
if variable is prefixed and suffixed with underscores
   result = object.send(variable.removeunderscores)
else
   result = variable
end

puts result

I was about to write this procedurally like this, but this is the type of thing that I think ruby can less clunkily if only I knew the language better.

What is a clean why to write this?

2
  • Maybe something like: result = variable.gsub!(/\A_|_\Z/, '')) ? object.send(variable) : variable? It's destructive and honestly not that elegant, but it is a one-liner if that's your kind of thing. Personally, I think your approach is plenty clean for what you're trying to do. Commented Feb 20, 2015 at 3:10
  • And actually, that one-liner isn't entirely correct. Sometimes having longer code is nice just to make sure you're doing things properly. Performance-wise, your current solution and that one-liner are pretty similar anyway. Commented Feb 20, 2015 at 3:11

1 Answer 1

1

There's nothing wrong with verbose code if it's clear to read IMO.

I'd do something like this using String#start_with? and String#end_with?:

variable = '__firstname__'
if variable.start_with?("__") && variable.end_with?("__")
   result = object.send(variable[2...-2])
else
   result = variable
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.