创建名称助手,将名字和姓氏分开 [英] creating name helper, to split first and last names apart

查看:48
本文介绍了创建名称助手,将名字和姓氏分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何获取属性并通过方法处理它以返回不同内容的帮助.但我以前从未这样做过,我不知道从哪里开始.我想尝试将 name:string 属性从George Washington"或John Quincy Adams"更改为只有George"和John"的名字.

I'm looking for some help on how to take an attribute and process it through a method to return something different. But I've never done this before and I' not sure where to start. I thought trying to change a name:string attribute from "George Washington" or "John Quincy Adams" into first names only "George" and "John".

我认为可能最好使用辅助方法,例如

I thought maybe a helper method would be best, such as

users_helper.rb

users_helper.rb

def first_name

end

然后调用@user.name.first_name,这是最初的工作方式吗?有人可以解释我接下来要去哪里才能将@user.name 传递到方法中吗?我见过这样的事情,但不太明白括号...

and then call @user.name.first_name, would this be initially how it would work? Can someone explain where I'd go next to be able to pass @user.name into the method? I've seen things like this but don't quite understand it the parenthesis...

def first_name(name)
  puts name
end

有人能分解一下 rails/ruby 是如何做这种事情的吗?非常感谢!

Could someone breakdown how rails/ruby does this type of thing? Thanks a lot!

推荐答案

括号(可选)包含参数列表.

The parentheses (which are optional) enclose the parameter list.

def first_name(full_name)
  full_name.split(" ")[0]
end

这里假设参数不为零.

> puts first_name "Jimmy McKickems"
Jimmy
> puts first_name "Jeezy"
Jeezy

但这不是字符串方法,因为您现在的假设是:

But this is not a string method, as your assumption is now:

@user.full_name.first_name # Bzzt.

相反:

first_name @user.name

这可以包含在模型类本身中:

This could be wrapped up in the model class itself:

class User < ActiveRecord
  # Extra stuff elided

  def first_name
    self.full_name.blank? ? "" : self.full_name.split(" ")[0]
  end
end

额外的代码检查名称是 nil 还是空格(blank? 来自 Rails).如果是,则返回一个空字符串.如果不是,则将其拆分为空格并返回结果数组中的第一项.

The extra code checks to see if the name is nil or whitespace (blank? comes from Rails). If it is, it returns an empty string. If it isn't, it splits it on spaces and returns the first item in the resulting array.

这篇关于创建名称助手,将名字和姓氏分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆