在進行 Sketchup 二次開發時,會涉及到對邏輯進行判斷,這些判斷也是程序員賦予程序思維的過程,下面通過代碼回顧下 Ruby 強大的流程控制:
model = Sketchup.active_model
ent = model.entities
# Ruby 語言實用特性
# 結構控制
x = "ASD"
a = 1
b = 2
# if判斷
if a > b
puts a
else
puts b
end
# case :條件
puts case x
when String; puts "String"
when Numeric then puts "Numeric"
when TrueClass,FalseClass ; puts "Boolen"
else
puts "Other"
end
x = 1
# while : 條件
while x <10
puts x
x += 1
end
x = 1
# until :直到...才停止
until x > 10
puts x
x += 1
end
for i in 1..10
puts i
end
# 改變結構
# return 返回參數,默認爲nil 跳出整個函數
# break 結束當前循環
# next 結束當前輪的循環到下一次
# redo
puts "======= redo ======="
# 讓循環從頭開始
i = 0
while i < 3
puts i
i += 1
redo if i == 3
end
################# 迭代器
# times 執行代碼多少次
3.times{
puts "666666666"
}
# each 類似於 for in
arr = [11,22,33]
arr.each{ |item|
puts item
}
# 也可以將塊寫成
arr.each do |item|
puts item
end
# map 將每個元素拿出後,執行塊加工後放回數組
[1,2,3].map{|item|
item * item
}
puts "---------"
# upto 從 1到10 遞增 打印的是 1到10的整數
1.upto(10) {|x|
puts x
}
# 對於 Numeric的迭代器
# 從 0 開始 以0.1爲增量 ,輸出到 PI
0.step(Math::PI,0.1){ |x|
puts Math::sin(x)
}
# 簡單應用例子
# 判斷面
ent.each{ |item|
if item.typename == "Face" && item.normal == [1,0,0]
puts "這是爲X軸的面"
end
}
# 獲取一個立方體的頂點數據
face = ent.add_face [[0,0,0],[100,0,0],[100,100,0],[0,100,0]]
face.pushpull -100
vertex_arr = []
ent.each do |entity|
if entity.typename == "Edge"
# 柔化邊緣線
if entity.start.position.x > 0 && entity.start.position.y > 0
entity.smooth = true
end
# 通過邏輯運算符,獲得不重複的矩陣
vertex_arr = vertex_arr | entity.vertices
end
end
vertex_arr.each{ |vertex|
puts vertex.position
}