创建名称助手,将名字和姓氏分开

编程入门 行业动态 更新时间:2024-10-28 03:18:09
本文介绍了创建名称助手,将名字和姓氏分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找有关如何获取属性并通过方法处理它以返回不同内容的帮助.但我以前从未这样做过,我不知道从哪里开始.我想尝试将 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.

更多推荐

创建名称助手,将名字和姓氏分开

本文发布于:2023-10-23 19:33:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:姓氏   助手   名字   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!