[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
posted @   Zhentiw  阅读(174)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 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 框架的概念及用反射技术开发框架的原理
点击右上角即可分享
微信分享提示