Ruby Call by reference is not working in each function?
excluded = "a", " an", " the", " at", " in", " on ", "since"
temp = excluded.split(",").each {|val| val = val.strip}
But I am getting the same array. Its not striping. I need to do t开发者_JAVA百科his in single line
i need the output in temp like ["a", "an", "the", "at", "in", "on", "since"]
try this
temp = ["a", " an", " the", " at", " in", " on ", "since"].map(&:strip)
As you can see from the docs Array#each
returns the original receiver (ary.each {|item| block } → ary
). What you want — as others have already pointed out — is Array#map.
Also your current code should raise a NoMethodError
because of calling split on an array. Assuming that excluded
is a string, the following will work:
excluded.split(",").map(&:strip) #=> ["a", "an", "the", "at", "in", "on", "since"]
Instead of using strip
you can also just change what you split on:
excluded.split(/,\s*/) #=> ["a", "an", "the", "at", "in", "on", "since"]
You want this?:
excluded = ["a", " an", " the", " at", " in", " on ", "since"]
stripped_excluded = excluded.collect{ |i| i.strip }
or shortcut:
stripped_excluded = excluded.collect(&:strip)
I think this should be the easier way:
temp = excluded.map(&:strip)
p temp
精彩评论