0

I have this object:

object.name

Sometimes name could be an array, sometimes it could be a string and sometimes an empty string. And so I assumed I could do something like this:

object.name do |name|
  name.is_a?(Array) ? name.join(' ') : name
end.presence

But this does not work, I can access name in the block but anything I do to it does not return.

What am I actually doing by passing name into a block like that? and how can I make this ruby lovely and work?

Thanks!

3
  • Does your #name method takes a block ? First check this . Commented Feb 9, 2014 at 14:29
  • 1
    Why in your case does name have multiple possible types? If you want to accept multiple types to set the value, that will mean you will want a different solution than if it inherently can hold multiple types of data. Commented Feb 9, 2014 at 14:30
  • I can not control what name is and how it is formatted as this is built on top of not so good code. Commented Feb 9, 2014 at 14:38

2 Answers 2

3

A simple way to do this is using the splat operator:

name = [ *object.name ].join(' ')

If object.name is just a string, the code will essentially be doing:

name = [ 'some string' ].join(' ')

Which will just result in 'some string'. However, if object.name is an array of strings, you'll end up with:

name = [ 'first string', 'second string', 'third string' ].join(' ')

Which will result in 'first string second string third string'.

Sign up to request clarification or add additional context in comments.

1 Comment

Another way to do this is with the Array() method: Array(object.name).join(' ')
1

Use a combination of tap and break.

object.name.tap do |name|
  break name.is_a?(Array) ? name.join(' ') : name
end.presence

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.