0

I have an object in a rails model that can either be a string or an array. In my view I have the following:

<% current_user.transaction[:account_name].each do |name| %>

If the object account_name is a string, then it throws an error.

I want to run something like this:

<% current_user.transaction[:account_name].each, if sting? each_line do |name| %>

using each_line if the object is a string, but using each if it is an array. I am not sure if this is the best solution. Any ways to make this work regardless of whether the object is an array or string?

2
  • Could you please full block so that I can modify the code Commented Jun 3, 2016 at 5:58
  • 3
    "I have an object [...] that can either be a string or an array"that is the problem you should fix. Commented Jun 3, 2016 at 6:22

3 Answers 3

6

You can use the splat operator. eg:

str = "hello"
arr = ["hi"]

[*str]
# => ["hello"] 
[*arr]
# => ["hi"]

So your code becomes

[*current_user.transaction[:account_name]].each do |name|
Sign up to request clarification or add additional context in comments.

2 Comments

Cool I didn't know this syntax before
Note that * calls to_a under the hood which can have undesired results if your objects implement a custom to_a, e.g. [*Time.now]
3
<% Array(current_user.transaction[:account_name]).each do |name| %>
   balaballa
<% end %>

Note that Array(element) would do nothing if you pass in an array, and try to convert the element with array if it is not an array.

If element is nil, then it would simply return you [], and nothing would be looped.

5 Comments

What if array is null?
@DineshSaini: Array(nil) = []
@DineshSaini: since Array(nil) give u empty array, it would be [].each
Correct we have to handle for nil in the loop, right? (+1 for you)
@DineshSaini: nope. if current_user.transaction[:account_name] is nil, then an empty array would be returned. (instead of [nil]). Meaning, [].each would never execute.
0
<% if current_user.transaction[:account_name].is_a?(String) %>
  <% current_user.transaction[:account_name].each_line do |name| %>
      balaballa
  <% end %>
<% elsif current_user.transaction[:account_name].is_a?(Array)%>
  <% current_user.transaction[:account_name].each do |name| %>
      balaballa
  <% end %>
<% end %>

1 Comment

You have missed the case if array is null and loop is calle

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.