Search code examples
rubyvariablesblock

Get value outside ruby block


I have

arr = [1,2,6,55,226]
arr.each do |a| p a end

How is it possible to get a outside do end?


Solution

  • Familiarize yourself with scopes.

    There are basically 3 scopes in Ruby: class/module/method definition scope, a block scope and a global (a more accurate term is 'script' scope). Scope means 'visibility', a block scope means a variable is not visible anywhere outside the do/end block, class/module/method definition scope means a variable is not visible anywhere outside the class/module/method definition.

    Your variable a is inside a BLOCK scope (between the do/end) and is only visible only between the do/end and not anywhere outside it.

    You can access any element of arr by its index:

    arr = [1,2,6,55,226]
    puts arr[0] #=> 1
    puts arr[1] #=> 2
    puts arr[3] #=> 6
    puts arr[4] #=> 226
    

    So you don't need a separate variable to access the content of the array when in fact, you can access it via arr. If you want to get all the elements of the array in 1 variable, you can use the join method:

    arr = [1,2,6,55,226]
    all_elements = arr.join(',')
    puts all_elements #=> 1,2,6,55,226
    

    Be aware that all_elements is now a String, not an Array. If you want to 'transform' each element, say, increase it by 1, you can do:

    arr = [1,2,6,55,226]
    array_increased_by_1 = arr.map do |each_element|
      each_element + 1
    end
    
    p array_increased_by_1 #=> [2, 3, 7, 56, 227]
    

    There are many methods of arrays in Ruby and many useful tutorials online for familiarizing you with them.