[Ruby] 1. Expression
- Unless to replace if !..?
- Unless可以理解为"除了"
if ! tweets.empty? puts "Timeline:" puts tweets end //Unless is more intuitive unless tweets.empty? puts "Timeline:" puts tweets end
Only nil is falsey
if attachment.file_path != nil attachment.post end //nil treated as false if attachment.file_path attachment.post end
- "" treated as "true"
- 0 treated as "true"
unless name.length // will never be false warn "User name required" end
- [] treated as "true"
Inline conditionals:
if password.length < 8 fail "Password too short" end unless username fail "No user name set" end //try inline if / unless fail "Password too short" if password.length < 8 fail "No user name set" unless username
Short-Circuit And
if user if user.signed_in? # .. end end // use && instead if user && user.singed_in? #.. end
Short-Circuit Assignment
result = nil || 1 --->1 result = 1 || nil --->1 result = 1 || 2 --->1
Deafult values - "OR"
tweets = timeline.tweets tweets = [] unless tweets //if nil, default to empty array tweets = timeline.tweets || []
Short-circuit evaluation
def sign_in current_session || sing_user_in end #sign_user_in: not evaluated unless current session is nil # but consider whether if / then would be more legile!
Conditional Assisgnment
i_was_set = 1 i_was_set ||= 2 #check if i_was_set or not first puts i_was set # --> 1 ------------- i_was_not_set ||= 2 puts i_was_not-set # ---> 2
options[:country] = 'us' if options[:country].nil? #use conditional assignment option[:country] ||= 'us'
Conditional return values:
if list_name options[:path] = "/#{user_name}/#{list_name}" else options[:path] = "/#{user_name}" end #assign the value of the if statement options[:path] = if list_name "/#{user_name}/#{list_name}" else "/#{user_name}" end
In method: automaticlly return the value:
def list_url(user_name, list_name) if list_name http://answer.com" else "http://question.com" end end
Case statement value:
client_url = case client_name when "web" "http://twitter.com" when "Facebook" "http://www.facebook.com" else nil end
Case - When / then
tweet_type = case tweet.status when /\A@\w+/ then :mention when /\Ad\s+\w+/ then :direct_message else :public end
分类:
Ruby
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2013-09-16 框架的概念及用反射技术开发框架的原理