ruby - Delete item from array without returning it -


i'm trying write method cause rspec test pass:

it "starts thing , move on"   class.method_1("name one")   class.method_1("name two")   expect(class.method_2).to eq "some string name one"   expect(class.method_3).to eq ["name two"] end 

method_1 adds name array, , method_3 returns array (defined in initialize method):

def method_1(name)   @array << name end  def method_3   @array end 

i figured pretty simple interpolate @array[0] string , use @array.delete_at(0) modify array. so:

def method_2   p "some string #{@array[0]}"   @array.delete_at(0) end 

but method returns "name one" instead of string. if comment out delete code, string returns array hasn't been modified. i've been in ruby docs long time #shift has same issue returning removed item.

i'm i've on complicated -- missing?

you can collapse down more conventional ruby this:

class mytestclass   attr_reader :array    def initialize     @array = [ ]   end    def push(s)     @array << s   end    def special_shift     "some string #{@array.shift}"   end end 

then in terms of usage:

it "starts thing , move on"   my_thing.push("name one")   my_thing.push("name two")   expect(my_thing.special_shift).to eq "some string name one"   expect(my_thing.array).to eq ["name two"] end 

using names push , shift consistent ruby conventions make purpose , action of method lot easier understand.

when comes implementation of method_3 forget can inline whatever want inside #{...} block, methods modify things. p method used display, won't return anything. return need have either last thing evaluated (implicit) or using return (explicit).


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -