The map method can be used to create a new array based on the original array, but with the values modified by the supplied block:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2.3.1 :032 > arr = [1,2,3]
=> [1, 2, 3]
2.3.1 :033 > arr.map { |a|2*a}
=> [2, 4, 6]
2.3.1 :034 > arr
=> [1, 2, 3]
2.3.1 :035 > arr.map! {|a|2*a }
=> [2, 4, 6]
2.3.1 :036 > arr
=> [2, 4, 6]
2.3.1 :037 > ['1','2','3'].map(&:to_i)
=> [1, 2, 3]
#same as
2.3.1 :038 > ['1','2','3'].map{ |i| i.to_i}
=> [1, 2, 3]
Variable
varibale scope
inner scope can access variables initialized in an outer scope,bu not vice versa
eg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
x = 0
3.times do
x += 1
end
puts x
#prints 3 to the screen
y = 0
3.times do
y += 1
x = y
end
puts x
# cant print, errors undefined local variable or method cuz x is not avaiavle as it is created with in the scope of the do/end block ,so its inner scope that's entirely outside of the execution flow.
variable type
constant variable
NAME
global variable
$name
class variable
@@name
instance variable
@name
local variable
name
some other e.g..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ruby name.rb
puts "What is your name?"
name = gets.chomp
puts "Hello " + name
#ruby name2.rb
puts "what is your first name?"
first_name = gets.chomp
puts "what is your last name?"
last_name = gets.chomp
puts "Great. so your full name is " + first_name + " " + last_name
近期评论