How to do the following in Ruby?
It does not work as expected because of pass-by-value params.
def validate! msg
if msg.is_a?(String)
msg = [ msg ]
end
end
#replace
could be used if msg were being replaced with another string.
How to do the following in Ruby?
It does not work as expected because of pass-by-value params.
def validate! msg
if msg.is_a?(String)
msg = [ msg ]
end
end
#replace
could be used if msg were being replaced with another string.
As the other answer has pointed out, you can't mutate in place a String into an Array.
You can reset the pointer with your defined method. But you can actually do one better by using #Array:
msg = 'string'
msg = Array(msg)
#=> msg = ['string']
msg = ['array']
msg = Array(msg)
#=> msg = ['array']
While some classes have instance methods that allow you to mutate objects, you cannot mutate an object into another class. In this case, you cannot mutate a String object into an Array object.
As you have it, your code will return [msg]
if the message is a string. Otherwise it would return nil. To make the method always return an array, you could use a ternary like so:
def validate! msg
msg.is_a?(String) ? [msg] : msg
end
# ...
my_msg = "message"
my_validated_message = validate!(my_msg) # => ["message"]
my_already_valid_message = ["different message"]
my_revalidated_message = validate!(my_already_valid_message) # => ["different message"]